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

337
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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