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
  • Select an option

  • Save bluetechy/c3c9de9258f9974cdeb09804a195f2a7 to your computer and use it in GitHub Desktop.

Select an option

Save bluetechy/c3c9de9258f9974cdeb09804a195f2a7 to your computer and use it in GitHub Desktop.

Revisions

  1. @born2net born2net created this gist Jul 10, 2019.
    30 changes: 30 additions & 0 deletions ngrx8_with_immer.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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...');
    })
    );