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()
}
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()
})
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.