React/Redux Tips: Better Way to Handle Loading Flags in Your Reducers

Sam Aryasa
StashAway Engineering
2 min readMar 8, 2018

TLDR; Use a separate reducer to store all isFetching flags instead of polluting all of your reducers.

So like everyone, you are using React for frontend, Redux for state management, and given that your app is complex enough, then it’s very likely for you to have run into this piece of code:

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 isFetching/errorMessage ☹️

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!

--

--

Sam Aryasa
StashAway Engineering

Clean Code Enthusiast, iOS/Android Mobile Application Developer, ♥ React Native