score:0

I also suffered from this problem for a day and got the solution. I just added in myCode the componentDidUpdate() method , and now everything working well. For the flow of the life cycle check out the life cycle image given in link.

score:0

In my problem I was making an API request and then setting the state with the returned values. I did not want the page to re-render so my state values where batching when updated and updated after 2-3 tries.

I fixed it when I noticed my post request was executing (sending data) during OPTIONS and then my GET request would retrieve data, then my POST would fulfill. If someone experiences the problem with API calls and reloading the page to update state is not an option maybe this will help.

setData(newEquipment).then(() => {
            grabData(nS).then(json => {
                if (json["cs"]) {
                    json["cs"].map((item: CMs) => {
                        if (item.label === "SE") {
                            item.metrics.map((mes: Ms) => {
                                if (mes.label === "1") {
                                    const a = mes.value;
                                    setSEs(a);
                                }
                            })
                        }
                    }
                    )
                }
            });
        });

score:2

As @Micheal stated, setState function stays pending, and first console.log works. Anybody who wants to see or experiment this situation, may have a look at my codesandbox.io example. Here, inside YesNoComponentWithClass, yes button logs empty for the first click, while no button logs the expected value.

score:44

The state is changing exactly the way it is supposed to. The problem is that your console.log statements immediately after your call to setState are firing before the new state is set.

From the docs:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

If you'd like to fire a console.log statement after the state transition completes, pass a function as a callback to setState().

this.setState({selectedFoods: newSelections}, () => {
    console.log(this.state.selectedFoods);
});

Related Query

More Query from same tag