A similar design pattern exists in ReactJS when we try to use setState() after calling an async function. In Redux we would not have this problem of course. However let's say you are rendering a location pin inside Google Map without the complexities of Redux state management. So all we want is:
- Geocode an address by calling Google Maps API
- Wait for the API response
- Set the map marker state so you get the pin at the right location
If step (3), the setState() function, is called before we get the API response, ReactJS is most definitely going to throw an error? Why? Because calling setState() before the component has fully mounted, or is still rendering, or is re-rendering, is a cardinal sin in ReactJS.
So to make sure that step (3) is always called at the very end, we can easily make use of the async functions. Note that in setState(), the common pattern to call it synchronously, is to bind it to a function. Checkout this working code below to understand what I am saying:
0 Comments