2
votes

I am writing a reactjs chat client and came across this in the documentation, which says

NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate(). If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

When a message is sent this function is called:

sendMessage: function(msg) {
    //Update the state of the app
    var message = {username:'User', message:msg};
    console.log(message.toString());
    this.state.datas.push(message);
    this.setState({datas: this.state.datas});
  },

What I am trying to do is append the new message to the list of messages then reset the state so the components rerender. This works fine but based on the documentation quoted above this isn't how this should be done. How should I go about updating the list of messages and updating the state without directly calling this.state.datas.push(message)?

1

1 Answers

4
votes

You can append your new message inside setState using concat. This way you are not mutating your state directly since concat returns a new array

sendMessage: function(msg) {
    //Update the state of the app
    var message = {username:'User', message:msg};
    this.setState({datas: this.state.datas.concat([message])});
}