mutate state property error still exists after using setState()

Viewed 64
  if (this.state.foody === "THALI" && this.state.cat === "NONVEG") {
      this.setState({ nonvegthali: this.state.nonvegthali++});
    } else if (this.state.foody === "THALI" && this.state.cat === "VEG") {
      this.setState({ vegthali: this.state.vegthali++ });
    } else if (this.state.foody === "SNACK" && this.state.cat === "VEG") {
      this.setState({ vegsnack: this.state.vegsnack++ });
    } else if (this.state.foody === "SNACK" && this.state.cat === "NONVEG") {
      this.setState({ nonvegsnack: this.state.nonvegsnack++});
    }

Before I wasn't using setState() and it was obvious to get the "Do not mutate state directly" error. But though after rectifying the code I am getting the same error in the console though the application is running fine and giving me intended output.

2 Answers

First thing the way you are doing setState isn’t right. Second is you are directly incrementing state value by using ++ which isn’t right.

setState is an asynchronous function which accepts an object but you are passing only value as param which isn’t right

Use prevState to increment the value. Please check below updated simplified solution

   const { foody, cat } = this.state;
   if (foody === "THALI" && cat === "NONVEG") {
         this.setState(prevState => ({nonvegthali: prevState.nonvegthali +1);
 } else if (foody === "THALI" && cat === "VEG") {
         this.setState(prevState => ({vegthali: prevState.vegthali +1);
 } else if (foody === "SNACK" && cat === "VEG") {
        this.setState(prevState => ({vegsnack: prevState.vegsnack+1);
 } else if (foody === "SNACk" && cat === "NONVEG") { 
      this.setState(prevState => ({nonvegsnack: prevState.nonvegsnack+1);
}

You are setting the state in wrong way. this.state.nonvegthali++ here you are still mutating the state.

Try to set state like this.setState({nonvegthali: this.state.nonvegthali + 1});

Related