Maciej Wira
Maciej Wira

Reputation: 159

React: async change of global state property

What is the best way for below scenario?

  1. There is a Loader component in App.js which is shown, when a property in global state (redux) property, e.g. loaderOn, is set to true
  2. There are couple of async api calls (in different components throughout the app), every which dispatches an action, which shows a loader (loaderOn: true)
  3. Problem: how to hide Loader after the LAST request is completed?

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

Answers (1)

technophyle
technophyle

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

Related Questions