skip to Main Content
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?

2

Answers


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

    useEffect(() => {
      console.log('basketdata',basketdata);
    }, [basketdata]);
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search