Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda