Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

341
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!