skip to Main Content

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


  1. Both of the ways you tried are almost correct but not quite.

    // your updating the state to an object and not an array
    setState((prevState) => ({ ...prevState,  newObj }))
    // Instead you should be spreading onto an array
    setState((prevState) => ([ ...prevState,  newObj ]))
    

    The other way is of similar issue.

    // Your setting the state to an object which contains the property state
    setState({ state: state.concat(newObj) });
    // update the state to an array of the concat array
    setState(state.concat(newObj));
    

    See https://react.dev/learn/updating-arrays-in-state for more info on correctly updating state on arrays.

    Login or Signup to reply.
  2. 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):

    setState((prevState) => ([ ...prevState,  newObj ]));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search