Angular 2 update global state as a side effect of updating a certain state

前端 未结 1 972
误落风尘
误落风尘 2020-12-07 03:11

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.

相关标签:
1条回答
  • 2020-12-07 04:10

    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.

    0 讨论(0)
提交回复
热议问题