user10794246
user10794246

Reputation:

Why is this counted as mutating state?

handleClick(event) {
let value = event.target.value;

this.setState({ question: (this.state.question += value) });

I get a warning:

Do not mutate state directly. Use setState() react/no-direct-mutation-state

if I try to load the page with this code.
How can I fix it so it doesn't give me this warning?
It says to use this.setState, but that's what I'm doing.

Upvotes: 0

Views: 78

Answers (3)

evkline
evkline

Reputation: 1511

This is considered mutating state because you are assigning a value to this.state.question in the expression (this.state.question += value). I have pasted a link to a Code Sandbox you can view to see how to correctly implement this behavior.

Code Sandbox

Upvotes: 0

Namoz
Namoz

Reputation: 540

The mistake is here :

this.state.question += value

+= is the operator used to add right operand to the left operand. You are trying to add value to this.state.question.

The correct way to do it is :

this.setState(previousState => ({ question: previousState.question + value }));

Upvotes: 1

ic3b3rg
ic3b3rg

Reputation: 14927

You're doing an unnecessary assignment addition to this.state.question - you only need addition here. Furthermore, when updating state based on a previous value, the docs state:

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

The proper way to update state based on a previous value is to pass in an update function that works off the previous value, i.e.:

this.setState(prevState => ({ question: prevState.question + value }));

Upvotes: 5

Related Questions