Home > Enterprise >  Why does JavaScript render data from the useEffect() hook but fails to render the data when put in t
Why does JavaScript render data from the useEffect() hook but fails to render the data when put in t

Time:05-23

I have a JSON file called teams.json that contains the basic structure ("name", "age", "country", "role", "team", and "image") in an object. I'm using React to use the function fetch() to retrieve the data from the local JSON file. When I call the useEffect (shown below) hook, the data is retrieved from the local JSON file and I'm able call a useState function to store the data in a state variable called data.

useEffect() function call

//file path
filePath = "/src/public/teams.json"
const getData = (file) => {
   fetch(file)
   .then(res => res.json())
   .then(data => setData(data))
   .catch(err => console.log("Error fetching data", err)
}
  
useEffect(() => {
   getData(filePath)
}, [filePath])

If I try to edit or access data within the useEffect() hook, the data is able to be retrieved without any problems, as such.

.then(data => console.log(data[0]))

This returns a json object that contains the necessary information.

{
  "name":"R",
  "image":"https://example.com",
  "team":"B",
  "role":"WB",
  "country":"American",
  "age":18
}

However, in the main body of my react App, if I try to obtain data from the data state, it gives me an error saying Cannot read properties of undefined, shown below.

Body of React App

return (
   <main>
      {data[0].country}
    </main>
  )

But I get this error:

Error Screenshot

I've tried solutions to previous forums from:

Stack Overflow Discussion Axios

Stack Overflow Discussion Error Axios

I've moved my project to the structure:

-src
--public
*some files*

and put the JSON file in the public folder. It reads it now but still doesn't render. I've also tried using axios but to no avail.

If this is an easy fix, sorry about that! Thanks for your help!

CodePudding user response:

Because the data isn't loaded yet.

Assuming your app is something like

function App() {
  const [data, setData] = React.useState();
  const getData = (file) => {
    fetch(file)
      .then((res) => res.json())
      .then((data) => setData(data))
      .catch((err) => console.log("Error fetching data", err));
  };

  useEffect(() => {
    getData(filePath);
  }, [filePath]);

  return <main>{data[0].country}</main>;
}

you're starting off with an undefined data.

Add a guard against that:

if(!data) return <>Loading...</>;
return <main>{data[0].country}</main>;
  • Related