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

Sam Aryasa
Mar 8, 2018 · 2 min read

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!

StashAway Engineering

StashAway’s Engineering Blog

Sam Aryasa

Written by

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

StashAway Engineering

StashAway’s Engineering Blog

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade