Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda