React/Redux Tips: Better Way to Handle Loading Flags in Your Reducers
TLDR; Use a separate reducer to store all isFetching flags instead of polluting all of your reducers.
This code would work fine until your app requires a lot more API calls — then half of your reducer code would be code to handle
Enter loading reducer
In StashAway, we solved this by creating a loading reducer that stores all API request states:
Then we can access those loading states using a selector in our component:
Since we don’t need to maintain any
isFetching flags, now our reducers will only need to care about storing data:
Ok maybe not that much simpler in this test code, but when your app requires you to make requests to more than 20+ APIs, it will make your life a tiny bit easier 😏
Can we combine API calls?
When building a real-world™ app, we might need to combine API calls (e.g. Only display todos page when both getUser and getTodos requests succeed). This is trivial with this approach:
How about error messages?
Handling API error messages is similar to handling loading flags, except when selecting which message to display:
Just as with many things in programming, there are many ways of doing things in React/Redux. This is simply our preferred way of doing it at StashAway.
We are always trying to find ways to improve at StashAway! Feel free to tell us what do you think in the comments!