gpbaculio
gpbaculio

Reputation: 5968

I cannot update my array state in react?

This is my code, can't figure out why this doesn't udpate my react state?

state = {
    popUpMessages:[]
  }
  popUpMessage(id,name) {
    console.log("id ",id,"name ",name)
    const addUserObject = { id, name };
    const newArray = [...this.state.popUpMessages, addUserObject]
    console.log("newArray = ",newArray)
    this.setState({ popUpMessages: newArray });
  }

In this code popUpMessage gets invoked to update the state:

<li  onClick={() => this.popUpMessage(this.props.id,this.props.name)}>{this.props.name}</li>

but my state is not updating and when I try to log, the previous user object is removed? I want my state to be array of objects something like this:

[{id:1, name: kim bok joo},{id:2, name: ria atayde}]

Upvotes: 0

Views: 81

Answers (2)

Christopher Messer
Christopher Messer

Reputation: 2090

As stated, not exactly recommended to do it this way. However, if you want to do it this way, this is all you have to do.

  popUpMessage(id,name) {
    const addUserObject = { id, name };
    const newArray = this.state.popUpMessages.concat([addUserObject])
    this.setState({ popUpMessages: newArray });
  }

Upvotes: 0

9000
9000

Reputation: 40884

The docs say that you should not depend on previous value of this.state when computing the new state.

But you do: const newArray = [...this.state.popUpMessages, addUserObject]

Try using a function that accepts the previous state and works with props, as shown in the docs.

Upvotes: 2

Related Questions