Trying to display fetched data stored in a state variable but it doesn't work

Viewed 14

I am trying to get data from the link below by using fetch and store it in 'dataStore' and display.

However, it keeps giving me an error and I believe my code tries to show the data before it is stored in 'dataStore'. I'm new to coding. tried to research and find a solution past weeks but couldn't. Please help. Thank you!

import "./App.css";
import { useEffect, useState } from "react";

function App() {
  let [dataStore, setDataStore] = useState([]);

  useEffect(() => {
    fetch(
      "https://raw.githubusercontent.com/Biuni/PokemonGo-Pokedex/master/pokedex.json"
    )
      .then((response) => response.json())
      .then((result) => {
        const { pokemon } = result;
        setDataStore(pokemon);
      })
      .catch((error) => console.log(error));
  }, []);

  return (
    <div>
      <div>{dataStore[0].name}</div>
    </div>
  ); // ending div
} //ending line

export default App;
1 Answers

Indeed it is trying to show dataStore before it is ready. To render the data when it is available, you should use conditional rendering (i.e. only render something given that a certain condition has been fulfilled). You can read more about that here: https://reactjs.org/docs/conditional-rendering.html.

Basically, check your dataStore length first, and if the length is above 0, then render the data. Should look something like this:

{dataStore.length > 0 &&
    <div>
      <p>{dataStore[0].name}</p>
    </div>
  }

Hope this helps!

Related