Reputation: 159
What is the best way for below scenario?
a) The above scenario is not quite good - true / false flag turns false after first request is completed
b) I was trying with a counter flag - +1 for each requested started and then -1 for each when completed - Loader hides at 0. But requests are async (and so is setting state from different places?), so it doesn't work either (setting counter flag depends on prev state and so parallel state changes give wrong final value)
Upvotes: 1
Views: 284
Reputation: 9118
The easiest solution to resolve your problem is defining separate loading flags for different async actions.
So, in redux's initialState
, you can have:
{
...
usersLoading: false,
productsLoading: false,
companiesLoading: false,
}
Then, you set it to true
/false
based on the loaded status of each data.
Finally, you can have a selector that evaluates the logical OR
of all loading flags like this:
state.usersLoading || state.productsLoading || state.companiesLoading
And in your App
component, connect the value of that selector to your prop, say, loading
, and render the Loader
component based on that:
{loading && <Loader />}
Upvotes: 1