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

halfer
  • 19,824
  • 17
  • 99
  • 186
Vishali
  • 1,307
  • 4
  • 23
  • 41
  • Does this answer your question? [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – Abe Aug 27 '22 at 17:31

2 Answers2

0

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

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

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
Alpha
  • 1,413
  • 3
  • 9
  • 23