CoinGecko API data undefined after re-render React JS

Viewed 260

Trying to render data from the CoinGekco API in my React component. It works on first render but if I leave the page or refresh, coin.market_data is undefined. I also tried passing coin to the useEffect() dependency array and that didn't work.

import React, { useEffect, useState } from "react";
import axios from "../utils/axios";
import CoinDetail from "./CoinDetail";

function CoinPagePage() {
  const [coin, setCoin] = useState({});

  useEffect(() => {
    const getCoin = () => {
      const coinid = window.location.pathname.split("/").splice(2).toString();
      axios
        .get(`/coins/${coinid}`)
        .then((res) => {
          setCoin(res.data);
          console.log(res.data);
        })
        .catch((error) => console.log(error));
    };
    getCoin();
  }, []);

  return (
    <div>
      <CoinDetail current_price={coin.market_data.current_price.usd} />
    </div>
  );
}

export default CoinPagePage;
1 Answers

The GET request only happens when rendering the parent page. Re-rendering the child component will not run the fetch code again. Instead of passing current_price as a prop to your <CoinDetail> component, you could try passing coinid and doing the fetch inside your detail page.

That way, when the page is refreshed, the request will be executed again.

Edit

If you try to access a not existing property on an object, your application will crash. What you could do to prevent this from happening is checking if the request is done, before trying to access the property.

One way you could do this by setting the initial state value to null

const [coin, setCoin] = useState(null);

Then, above the main return, you could check if the value is null, if it is, return some sort of loading screen

if(coin === null) return <LoadingScreen />;

// main render
return (
  <div>
    <CoinDetail current_price={coin.market_data.current_price.usd} />
  </div>
);

This way, when the fetch is done, the state gets updated and the page will re-render and show the updated content.

Related