I want to achieve setting a global state while also requesting data from an api and storing that in the state as well, but in another location than the global state.
Storing an isLoading
indicator in a central place is a similar to what is sometimes done with error information. One solution for storing a central error involves using a reducer that ignores actions' types and looks only to see if they contain an error
property.
If you were to adopt a suitable naming scheme for your effects' action types, you could do much the same thing with isLoading
.
One possible naming scheme could be:
SOME_ACTION_REQUEST
SOME_ACTION_RESPONSE
SOME_ACTION_ERROR
With such a scheme, the following reducer would examine the action types and set the isLoading
state accordingly:
export function isLoadingReducer(state: boolean = false, action: Action): boolean {
if (/_REQUEST$/.test(action.type)) {
return true;
} else if (/(_RESPONSE|_ERROR)$/.test(action.type)) {
return false;
} else {
return state;
}
}
Using a boolean
value for isLoading
assumes that you would not have concurrent asynchronous effects, so if that's an issue, you could extend the reducer to use a counter instead.
If you wire things up this way, the isLoading
indicator doesn't need to know anything about individual effects and vice versa.