jude
jude

Reputation: 43

React setState not updating state immediately

I have to select the dropdown twice to update the details.

     <Dropdown
        onSelect={(e) => {
          if (e === "YES") {
            this.setState({
              BasePlantsSiteHire: "",
            });
          } else if (e === "NO") {
            this.setState({
              BasePlantsSiteHire: "N",
            });
          } else if (e === "ONLY") {
            this.setState({
              BasePlantsSiteHire: "Y",
            });
          }
          this.componentDidMount();
          console.log(
            "Status Updated: ",
            this.state.BasePlantsSiteHire
          );
        }}
      >
        <Dropdown.Toggle style={{ background: "none", border: "none" }}>
          <CIcon name="cil-settings" />
        </Dropdown.Toggle>
        <Dropdown.Menu className="pt-0" placement="bottom-end">
          <Dropdown.Item
            eventKey="YES"
            name="YES"
            key="YES"
            value="YES"
          >
            SubHire Include
          </Dropdown.Item>
          <Dropdown.Item eventKey="NO" name="NO" key="NO" value="NO">
            SubHire Exclude
          </Dropdown.Item>
          <Dropdown.Item
            eventKey="ONLY"
            name="ONLY"
            key="ONLY"
            value="ONLY"
          >
            SubHire Only
          </Dropdown.Item>
        </Dropdown.Menu>
      </Dropdown>

My problem is that when I call the select dropdown it is not updating immediately, Need to select twice to get the action and console.log the state.

enter image description here

Upvotes: 0

Views: 8376

Answers (2)

Rishav Maskey
Rishav Maskey

Reputation: 191

React's setState function is asynchronous. What you're experiencing is completely normal behavior. If u need to do something after the state has been updated, u can pass in a callback function to setState as a second argument like so:

    this.setState({
                ...
            }, () => { 
                  console.log(
                    "Status Updated: ",
                    this.state.BasePlantsSiteHire
                  );
                  // do something here
     })

Also, please don't make calls to componentDidMount explicitly, those are component life cycle methods that will be called by React itself throughout the lifecycle of your component!

Upvotes: 3

Evgenii
Evgenii

Reputation: 143

This happens because setState is an asynchronous function. You should callback:

 this.setState(prevValue => {
   // someLogic
   return newState.
})

You can find more information there:

Upvotes: 1

Related Questions