Buddy Bob
Buddy Bob

Reputation: 5889

setState not updating state even with callback and handleFunction - ReactJs

I have a handle function which is called in another component. This passess a value called data, which I want to update into my state.

//basic code
initialState = {
  wordCount:"Some Value"
  text: "Some value"
}
class Home extends Component{
  state = initialState;
  handler(data){
    console.log('Arrived',data)
    this.setState({wordCount:data,text:GetText(data,this.state)});
    this.validation();
  }
  validation(){
    console.log(this.state.wordCount)
  }
  render(){
  return (
      <div><Component handlerFunc={this.handler.bind(this)}</div>
  )
  }
       

Printing out data in my handler function I do receive the right information as a string. The I use setState to replace wordCount's initial value with data. I do the same with text. GetText returns a string.

But when validation is run, my state is exactly the same. How could this be?

Upvotes: 0

Views: 132

Answers (1)

Rajesh Paudel
Rajesh Paudel

Reputation: 1155

Note: setState in react is asynchronous.

This means there is no guarantee that state will have changed by the next statement. What you can do to avoid this is setState accepts callback which will be called when set state finishes.

this.setState(
   {
       wordCount:data,
       text:GetText(data,this.state)
   }, 
   () => { 
    // Gets called when setState updates the state
    this.validation() 
});

Upvotes: 1

Related Questions