Reputation: 573
This is how you add one element to items
const [items, setItems] = useState
setItems([...items, newElm ]);
But what if I wanted to add/concatenate an array of elements to items. This doesn't work
const [items, setItems] = useState
setItems([...items, newArr ]);
How would I do this?
Upvotes: 0
Views: 646
Reputation: 1340
You have to spread the new array just as the items array.
Remember that the recommended way to merge the new items
array with your current state is as follows:
setItems(prevState => ([...prevState, ...newArray]))
In this way you can ensure that prevState
will have an updated value.
Upvotes: 1
Reputation: 1
Spread the elements of the new array into the state
const [items, setItems] = useState setItems([...items, ...newArr ]);
Upvotes: 0