how to manage complex redux state for different async calls?

233 views Asked by At

I have always thought about this question when you have a scenario with a redux slice and you want to fetch multiple different APIs or do some async calls on some events simultaneously, how would you build your reducer and redux state?

let me explain an specific scenario:

Imagine I want the result of 2 APIs and I have this state:

{
 data1: null,
 data2: null,
 loading: false,
 error: false,
}

And I want to fetch two calls to get the data on react component mount, should I declare two loadings for these two calls or what? what is the best practice on these kinds of stuff? you can also imagine two or three different event clicks which call an async Fetch API too.

1

There are 1 answers

1
Martin Kadlec On

What is the best practice on these kinds of stuff?

There really isn't one, because the answer depends a lot on opinion, architecture vision and specific scenario. In broader sense, this leads to questions like whether to fetch data in react or redux in the first place and it is the reason why there is so many state management libs etc.

I think, especially today, that developers picking redux & its middleware to handle fetching do so often because they prefer to think of all data received from backend as a global state - hence the use of global state management library. That way we can make any such data easily available to any part of our application, whether it is the view layer like react or some logic layer like redux sagas.

With the above in mind, it would make sense to structure the state of the data and metadata (like loading etc.) to make sure it really is easy to access and reuse at any place - and so in your case, to keep the loading/error state for each such slice.

At the same time, maybe you are reasonably sure that two slices of data are only ever going to be used together and so having extra metadata is a waste of time, so as I said in the beginning it all depends also on a specific case from all kind of perspectives.

Also, if all you use sagas for is fetching, something like react-query or rtk-query (if you want global state management for other things) might be a better pick and would make some of these architecture decisions much easier as those libraries are much more opinionated. Don't get me wrong, sagas are great and I personally prefer them in most cases to all the other solutions, but they do require in my experience a strong vision and firmer grasp on your app architecture.