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

309
Visualizações
Cannot read properties of undefined (reading '0') while passing values to another component

I have written the following code to pass values to infobox but i am getting an error uncaught TypeError: Cannot read properties of undefined (reading '0').please tell where i am wrong.

import React,{useState} from 'react'
function App() {
   const [specificState, setSpecificState] = useState({});
   const jsondata1 = await fetch('https://covid-19-fastest-update.p.rapidapi.com/summary');
    const myData1 = await jsondata1.json();
    const indData = myData1.Countries[77];
   const getdata=()=>{
    const temp =[];
     temp ['Confirmed']= [indData.NewConfirmed, indData.TotalConfirmed]
     temp['Recovered'] = [indData.NewConfirmed, indData.NewConfirmed - indData.TotalDeaths]
     temp ['Deaths']= [indData.TotalDeaths, indData.NewDeaths] 
    setSpecificState(temp);
   }
   useEffect(() => {
    getdata();
   }, [])
   
  return (
    <div> <InfoBox title="Coranavirus cases" cases={ specificState.Confirmed[0] } 
   total={ specificState.Confirmed[1] } />  </div>
  )
}

export default App
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You need to make your fetch requests inside of useEffect.

update your get data function like this;


   const getdata=()=>{
  const jsondata1 = await fetch('https://covid-19-fastest-update.p.rapidapi.com/summary');
    const myData1 = await jsondata1.json();
    const indData = myData1.Countries[77];
    const temp =[];
     temp ['Confirmed']= [indData.NewConfirmed, indData.TotalConfirmed]
     temp['Recovered'] = [indData.NewConfirmed, indData.NewConfirmed - indData.TotalDeaths]
     temp ['Deaths']= [indData.TotalDeaths, indData.NewDeaths] 
    setSpecificState(temp);
   }

remove the fetch and other operations from the body of the component.

then you need to wait for state to be fetched, you need to render your component conditionally.

  return (
    <div> {spesificState.Confirmed && <InfoBox title="Coranavirus cases" cases={ specificState.Confirmed[0] } 
   total={ specificState.Confirmed[1] } /> } </div>
  )
}

maybe something like this.

about 4 years ago · Juan Pablo Isaza Relatório

0

When state is initially loaded, specificState is an empty object so no Confirmed property is found (undefined)

So at first render, this will throw this exception. When useEffect runs and retrieves results, then this property is loaded and then you can use your InfoBox class.

So instead use

return (
   {specificState.Confirmed ?  <div> <InfoBox title="Coranavirus cases" cases={ specificState.Confirmed[0] } 
   total={ specificState.Confirmed[1] } />  </div> : null }
  )
about 4 years ago · Juan Pablo Isaza Relatório

0

You can create statement using if operator in useEffect hook, because right now your fetched data is not uploaded yet when you try to use indData. Just cover your getdata function in useEffect like this:

useEffect(() => {
   if (indData) {
     getdata();
   }
}, [indData])

Also, you need to add extra values while passing cases and total attributes in InfoBox component, just pass empty array using | []

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