Search code examples
javascriptreactjsreact-class-based-component

React class based components update state based on previous state


I have class based components in my React application. I have a checkbox that will pass a string and a number value when checked.

My state currently looks like this:

  state = {
    checked: [],
    checkedWeight: 0,
  };

And what I could like to achieve is to append the string value passed to my handleCheckClick to my "checked" array as well as add the weight value to the total on checkedWeight (and subtract the weight and remove the string from "checked" when un-checking the box).

All variations I have tried of this create an infinite loop. For example, the next function creates an infinite loop on both cases.

 handleCheckClick = (name, weight) => {
    const joined = this.state.checked.concat(name);
    this.setState({ checked: joined });
    this.setState({ checkedWeight: this.state.checkedWeight + weight });        
  };

The next implementation does not seem to be working either:

handleCheckClick = (name, weight) => {
    this.setState(prevState => ({ checked: [...prevState.checked, name] }));
}

How can I avoid this loop without hooks?


Solution

  • Try the following:

    handleCheckClick = (name, weight) => {
      this.setState(prevState => ({ 
        checked: [...prevState.checked, name], 
        checkedWeight: prevState.checkedWeight + weight
      })
    }
    

    I can't see this causing an infinite loop. Something else might be causing that.