0

I want to clear all data in a state that contains a list of items:

const [items, setItems] = useState([]);

When I try the code below, and add items in it again, it doesn't clear the state as expected:

setItems([]);
var newItem = {
    ...
}
setItems([...items, newItem])

What did I missed?

DouzeBri DouzeBra
  • 117
  • 1
  • 2
  • 13
  • You overrule the `setItems([])` by calling `setItems([...items, newItem])` in the same tick. The last `setItems` call also includes `items` property, which not have been updated yet. To clear the items and only include the `newItem` use `setItems([newItem])` instead. – Chris Oct 28 '21 at 09:06

0 Answers0