Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

243
Vistas
Why does JavaScript render data from the useEffect() hook but fails to render the data when put in the function body?

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!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda