henrybbosa henrybbosa - 24 days ago 7
React JSX Question

this.setState with not working

I am trying to set state and then call another function with the current state just after setting it.

I have this kind of code

this.setState({
candidates : diCandi
},()=>{
this.createDataSource(this.state)
console.log("The state is=>",this.state);
});


I want to call
this.createDataSource(this.state)
with the state i just updated.
Its not working I wonder why. Is there anything i am doing wrong

Infact when i log out the state. I never see the code in the logs.

Answer Source

class App extends React.Component{
  constructor(props){
    super(props)
    this.state = { candidates: "no candidates" }
  }
  
  shouldComponentUpdate(){
    return false;
  }
  
  buttonClick(e){
    this.setState({candidates: "diCandi"}, () => console.log("updated"))
  }
  
  render(){
    return(
    <div>
        <button onClick={this.buttonClick.bind(this)}>set candidates</button>
        <b>{this.state.candidates}</b>

      </div>
    )
  }
}

const MOUNT_NODE = document.getElementById('container')
ReactDOM.render(<App />, MOUNT_NODE)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">

The code should work as mentioned earlier by Sagar, the callback on this.setState() only kicks in after the state has been set. The callback works even if shouldComponentUpdate is returning false