Home > Mobile >  How to print updated state value in React Native
How to print updated state value in React Native

Time:08-29

const filteredata=  basketdata.filter(obj => {
    return obj.id !== item.id;
});
setBasket([...filteredata]);
console.log('basketdata',basketdata);

I am removing items from my array when same items available. After removing item trying to print the array in console but it doesn't printing the actual value. Also I know that setState() will not update immediately.

How can I solve this issue?

CodePudding user response:

Use a useEffect-hook to listen for changes to the variable

useEffect(() => {
  console.log('basketdata',basketdata);
}, [basketdata]);

CodePudding user response:

The main issue was filter function does not change the original array it returns a new array thats why when you were printing the basketdata it was showing all the item.

Solution: print the filteredata in the console log.

const filteredata = basketdata.filter((obj) => {
      return obj.id != item.id;
    });
    setBasket([...filteredata]);
    // console.log("basketdata", basketdata); // don't print this
    console.log("filteredata", filteredata);// print this
  • Related