I have:
[state, setState] = useState([
{
item: apple,
color: red,
},{
item: banana,
color:yellow,
}])
I want to add the following to the array :
{
item: grape,
color: purple
}
I have tried
setState((prevState) => ({ ...prevState, newObj }))
and
setState({ state: state.concat(newObj) });
But the the data is not being added to the state
2
Answers
Both of the ways you tried are almost correct but not quite.
The other way is of similar issue.
See https://react.dev/learn/updating-arrays-in-state for more info on correctly updating state on arrays.
You you have array of items as your initial state, but later you are setting an object as a new state.
In order to add new data you have to use array (square brackets):