简体   繁体   中英

Page tries to render before data is loaded from API - React

I am pulling data from a cyrpto API that loads data of 250 coins. When I pull only 100 coins, the data is rendered fine. When I see it to 250, the data is rendered before loaded and it gives an error. The data is loaded in console when I log 250 coins.

The data function:

const fetchCoinData = async () => {
    setLoading(true);
    const fetchedCoinData = await getCoinsData();
    setData(fetchedCoinData);
    setLoading(false);
  };

  useEffect(() => {
    fetchCoinData();
  }, []);

The API call:

export 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=false&price_change_percentage=1h%2C24h%2C7d`
    );
    return response.data;
  } catch (e) {
    console.log(e);
  }
};

It would help if you wrapped your axios response in a promise and change your state in the then function since it seems like your state is updating before your API call is over. Something like the followng would help.

await getCoinsData()
    .then(fetchedCoinData => {
        setData(fetchedCoinData))
        setLoading(false)
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM