I'm new to React and I'm sure this is a very simple solution. However, I can't seem to figure out how to properly set the state of a component to be the response from a REST call I make.
Here's the response object format I'm returning
export interface CoinMarketChartsAll {
oneDay: Array<CoinChartDataMapped>;
sevenDay: Array<CoinChartDataMapped>;
oneMonth: Array<CoinChartDataMapped>;
}
And here's my functional component where I fetch this data and try to set the state equal to it
const [loading, setLoading] = useState(true);
const [cryptoData, setCryptoData] = useState<CoinMarketChartsAll>();
useEffect(() => {
fetchMarketChart();
}, []);
const fetchMarketChart = async () => {
setLoading(true);
if (!cryptoData) {
getCoinMarketChart('lgcy-network').then((response) => {
setCryptoData(response);
setLoading(false);
})
.catch((error) => {
console.log(error);
setLoading(false);
});
}
}
I tried logging the output inside the if statement and cryptoData was always equal to undefined. Until I toggled the if statement to be
if (cryptoData) {
Then it would load it into the state, but when I reloaded the page it would never make it into the if statement. Can anyone please point out what I'm doing wrong? Thanks!