Component renders and gives an error before the data is completely loaded from the API
I am pulling data from a crypto coin API. It has 250 coins data in one request. But if I load all of them, the data is not loaded and component tries to render which gives an error. I am following the regular practice of await and useEffect but still the error is persistent.
const Home = () => {
const [search, setSearch] = useContext(SearchContext);
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const getCoinsData = async () => {
try {
const response = await Axios.get(
`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=100&page=1&sparkline=true&price_change_percentage=1h%2C24h%2C7d`
);
setData(response.data);
setLoading(false);
} catch (e) {
console.log(e);
}
};
useEffect(() => {
getCoinsData();
}, []);
const negStyle = {
color: "#D9534F",
};
const positiveStyle = {
color: "#95CD41",
};
return (
<div className="home">
<div className="heading">
<h1>Discover</h1>
<hr className="line" />
</div>
{!loading || data ? (
<div style={{ width: "100%", overflow: "auto" }}>
<table *the entire table goes here* />
</div>
) : (
<img className="loading-gif" src={Loading} alt="Loading.." />
)}
</div>
);
};
export default Home;
This is the entire code. Still when I try to refresh, it gives errors based on how much data loads. Sometimes, .map function is not defined or toFixed is defined etc. It does not keep loading till the whole data is loaded.
Solution 1:
Can you show the errors and how did you initialize your state loading
and data
so we can debug better ?
Otherwise, what I usually do in this case is:
if (!loading && data) return <Table />;
return <img className="loading-gif" ... />;