Mahdiyar Zerehpoush
Mahdiyar Zerehpoush

Reputation: 366

Do not mutate state directly. Use setState()

I see similar questions in this field but my question is different from these as i don't set state directly from this.state . my code is

state = {
count: 0};

handleIncrement = product => {
    console.log(product);
    this.setState({ count: ++this.state.count });
};

as you see i don't set state directly but given me this error at this line

Upvotes: 3

Views: 3317

Answers (3)

Darvesh
Darvesh

Reputation: 563

You shouldn't mutate the state directly you can do as follows.

   this.setState(prevState => ({
        count: prevState.count+1;
    }));

Upvotes: 5

Daksh M.
Daksh M.

Reputation: 4817

When you do this:

++this.state.count

This tries to mutate the state directly, because you're trying to do this:

this.state.count = this.state.count + 1

which changes the current value of state, but you should do this using setState not directly as the error says.

Do this instead:

this.setState({ count: this.state.count + 1 });

As a best practice, use a callback to avoid a race condition, such as:

this.setState(prev => {
    return {
        count: prev.count + 1,
    };
});

Upvotes: 7

Jordan Sykes
Jordan Sykes

Reputation: 71

You can functionally update the state, therefore it takes the previous value of state, the props you are passing it and calculates the next state like so:

handleIncrement = product => {
    console.log(product);
    this.setState((state, props) => {
     return {
      count: state.count + 1
     }
    });
};

Upvotes: 3

Related Questions