Can't enable the disable button using setState

Hi,

I am trying to enable a button based on whether the 2 input fields have some data in it. The input fields are controlled bu component state. I want to enable the “ADD” button as soon as there is some value in the 2 input fields but right now it is enabled only when I type the 2nd alphabet in it. Can’t figure out why?
Can anyone check the AddDetailsComp component in the app and let me know what am I missing here? App link: https://stackblitz.com/edit/godutch-app?file=Components%2FAppDashboard.js

To see the preview for the same, click on “3 dots” in nav bar, click add friend and a modal will appear. Add a name, number or email there and click “add to Go-dutch”. Once you do that, a new modal will appear which is all about the AddDetailsComp. I can’t figure out why adding just one alphabet in the 2 fields is not enabling the add button. See the screenshot below for your reference:

That’s because setState is asynchronous. You need to call handleAddBtn after name and contactInfo is set. You can do it by passing this.handleAddBtn as a second parameter to setState:

  handleName = e => {
    let name = e.target.value;
    this.setState(prevState => {
      return { name };
    }, this.handleAddBtn)
    // this.handleAddBtn();
  };

  handleContactInfo = e => {
    let contactInfo = e.target.value;
    this.setState(prevState => {
      return { contactInfo };
    }, this.handleAddBtn)
    // this.handleAddBtn();
  };
3 Likes

While I knew setState is async and the setState calls can be queued, I didn’t know we can have a callback function in the setState as the second argument. Something new I learned today. Thank you.

And it worked!

1 Like