Home > OS >  React Help - Why do i need to click twice to update state and call function?
React Help - Why do i need to click twice to update state and call function?

Time:11-10

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);
      
    }

CodePudding user response:

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.

  • Related