Home > database >  Uncaught TypeError: Cannot read properties of null (reading '0') when fetch the API link i
Uncaught TypeError: Cannot read properties of null (reading '0') when fetch the API link i

Time:05-02

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

CodePudding user response:

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.

CodePudding user response:

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]);
  • Related