Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!