Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Help – Why do i need to click twice to update state and call function?

I have some buttons within my app that call handleTypeChange function below – my issue is that i have to click them twice for them to update state and call the getCOBs function correctly.

Can anyone point out what i am doing wrong?


    handleTypeChange(event){
    this.setState({filtertype: event.target.getAttribute('value')});
  
      if (event.target.getAttribute('value') === "Commercial")
      {
        this.setState({filtercommercial: 'True'});
        this.setState({filterpackage: 'False'});    
      }
      else if (event.target.getAttribute('value') === "Package")
      {
        this.setState({filtercommercial: 'False'});
        this.setState({filterpackage: 'True'});    
      }
      else{
        this.setState({filtercommercial: 'False'});
        this.setState({filterpackage: 'False'});    
      }
      getCOBs(this.state.filtercommercial, this.state.filterpackage).then(populateCOBDropdown);
      
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

this.setState function needs some time to save the states.

handleTypeChange(event){
  const value = event.target.getAttribute('value');
  this.setState({
    filtertype: value,
    filtercommercial: value === "Commercial"? "True" : "False",
    filterpackage: value === "Package"? "True" : "False",
  }, () => {
    getCOBs(this.state.filtercommercial, this.state.filterpackage).then(populateCOBDropdown);
  });          
}

The callback function of this.setState will be called after states are updated.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading