Skip to content

Instantly share code, notes, and snippets.

@bluetechy
Forked from born2net/ngrx8_with_immer.ts
Created October 17, 2020 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluetechy/c3c9de9258f9974cdeb09804a195f2a7 to your computer and use it in GitHub Desktop.
Save bluetechy/c3c9de9258f9974cdeb09804a195f2a7 to your computer and use it in GitHub Desktop.
ngrx 8+ with immer and support for on() within reducer
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