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: