Vincent Ritter

I was banging my head on why some of my initial data check didn't work in React when setting a state on my component. Turns out that setting states is asynchronous, so there is no guarantee that state is updated straight away (when I was running the first check to then return a list of items).

The following code didn't work - only after a second state change did it begin to work:

this.setState({   
    selectedHamburger: selected
});
this.updateHamburgerDisplay();

(Don't ask - I made up that state and method)

However, when first loading the page, there was no "Hamburger Display" showing. It was empty.

Doing a bit of research I found out that `setState` actually has a callback function for when it has updated. So, simply calling my method on the callback worked a treat.

this.setState({
    selectedHamburger: selected
}, this.updateHamburgerDisplay);

I know... basic stuff. But good to find out. A small "aha" moment. Maybe someone will find it interesting.

Close