in

Using .filter() for React’s useState setter within a .forEach() loop


I need to remove objects from an array stored within cart‘s state.

This should be done by iterating through the strings stored within selectedCart‘s array.
For each string for selectedCart that matches cart‘s string (within an object/key), it should remove that entire object.

The code below seems to only remove the object that matches selectedCart‘s string in last index ONLY.

So if it’s

const [selectedCart, setCart] = ['test', 'this', 'data']

And each object’s key (name) has the value of all these strings… only the string ‘data’ gets filtered.
If I switch the first and last positions (so ‘test’ is last), only the string ‘test’ gets filtered.

const [cart, setCart] = useState([])
const [selectedCart, setCart] = []

selectedCart.forEach(selected => 
      setCart(cart.filter(entry => entry.name !== selected))
    )



Source: https://stackoverflow.com/questions/70552117/using-filter-for-reacts-usestate-setter-within-a-foreach-loop

Dynamic object-oriented programming support for the Go language

Bootstrap 5 form validate and ajax post