-
-
Save bluetechy/c3c9de9258f9974cdeb09804a195f2a7 to your computer and use it in GitHub Desktop.
ngrx 8+ with immer and support for on() within reducer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {createReducer} from '@ngrx/store'; | |
import {on} from "@ngrx/store"; | |
import produce, {Draft} from "immer"; | |
export const initialUserState: IUserState = { | |
knownUsers: [user1, user2], | |
selectedUser: null, | |
scenes: null | |
}; | |
export function produceOn<Type extends string, C extends FunctionWithParametersType<any, object>, State>( | |
actionType: ActionCreator<Type, C>, | |
callback: (draft: Draft<State>, action: ActionType<ActionCreator<Type, C>>) => any, | |
) {return on(actionType, (state: State, action): State => produce(state, (draft) => callback(draft, action)));} | |
export const loadRequest = createAction('[Scenes API] Scene Load Request', props<{ businessId: BusinessId }>()); | |
export const loadSuccess = createAction('[Scenes API] Scene Load Success', props<{ scenes: List<SceneModel> }>()); | |
// ngrx 8+ with immer and support for on() within reducer | |
const featureReducer = createReducer( | |
initialUserState, | |
produceOn(loadSuccess, (draft, action) => { | |
draft.scenes = {myList: [1,2,3]}; | |
}), | |
produceOn(loadFailure, (draft, action) => { | |
draft.scenes = {myList: []}; | |
console.log('error loading...'); | |
}) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment