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

343
Visualizações
Uncaught TypeError: Cannot read properties of null (reading '0') when fetch the API link in REACT

I have successfully fetched the products. But when I console log it shows null after then it shows the array of 10 products.

const [datas,setDatas]=useState(null);
const [loading,setLoading]=useState(false);

  useEffect(()=>{

        fetch('products.json')
        .then(result =>result.json())
        .then(data => setDatas(data));
        setLoading(true);
        
    },[]);



    console.log(datas);//no error occured

[![it shows both null and 10 products][1]][1]

But when I'm accessing the 0th index of datas array, it shows an error! here is my code

const [datas,setDatas]=useState(null);
const [loading,setLoading]=useState(false);
    useEffect(()=>{

        fetch('products.json')
        .then(result =>result.json())
        .then(data => setDatas(data));
        setLoading(true)
        
    },[]);

   console.log(datas[0]);//error occured

[![error occured][2]][2]


  


  [1]: https://i.stack.imgur.com/IFbqd.png
  [2]: https://i.stack.imgur.com/CD1AH.png
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The result is usually wrapped in a type with properties like this;

export type ResponseResult<T> = {
    status: number;
    message?: string;
    data?: T;
    success?: boolean;
};

Replace setDatas(data)); with setDatas(data.data)); and see if that works better.

Also you might have problems as the call is asynchronous - you're not guaranteed to have the data ready unless you console.log in the .then() part of the call.

Something like

fetch('products.json')
   .then(result =>result.json())
   .then(x => {
       setDatas(x.data);
       console.log(datas);
   });
   setLoading(true);

...should work.

about 4 years ago · Juan Pablo Isaza Relatório

0

As receiving api response and setting state is asynchronous, you need to check that the state datas is not undefined, just change the line to:

if(datas && datas.length>0)
   console.log(datas[0]);
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