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

191
Views
React - Return function value to setState

I need to return the function's checkSuggestionList value to this.state.validSearchParentInput . The function checkSuggestionList returns the proper value but it does not get passed to this.state.validSearchParentInput. I believe setState sets the value before the function checkSuggestionList finishes.

  checkSuggestionList = (newValue) => {
      for (let i = 0; i < nodes.length; i++ ) {
        let node = nodes[i].name
        console.log('node: ' , node)
        if (node.toLowerCase() === newValue.toLowerCase()) {
          console.log('did find case') 
          return true
        } else {
          console.log('didn\'t find case')
        }
        return false
      }
  }

  searchParents__onChange = (event, { newValue, method }) => {
    this.setState({
      validSearchParentInput: this.checkSuggestionList(newValue),
      searchParentsValue: newValue
    })
    this.checkProgress()
  }
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The setState function of a React component is not guaranteed to be synchronous, but may be executed asynchronously for performance reasons.

You are likely reading the state before the change has been applied.

To resolve this, you could utilize setState's second parameter, which takes a callback function that is executed after the state transition was made:

this.setState({
  validSearchParentInput: this.checkSuggestionList(newValue),
  searchParentsValue: newValue
}, function() {
    this.checkProgress()
})
over 4 years ago · Santiago Trujillo Report

0

setState actions are asynchronous. This is explained in documentation of setState.(For reference: https://facebook.github.io/react/docs/react-component.html#setstate)

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

over 4 years ago · Santiago Trujillo 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!