How do I properly set the state to a response output in React using Typescript?

Viewed 33

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!

1 Answers

I tried logging the output inside the if statement and cryptoData was always equal to undefined.

That is simply because the state setter takes effect after a "tick": you can do setCryptoData(true), but cryptoData will remain undefined until that next tick.

when I reloaded the page it would never make it into the if statement

When you first changed your if condition, React Hot Module swap kicked in and updated your component, while preserving its current state, therefore your cryptoData state was already truthy.

But after page reload, you get a "fresh" component instance, which starts with a freshly initialized state, i.e. with undefined value, since you define it with no initial value (useState<CoinMarketChartsAll>(/* no initial value */))

Related