Created
July 10, 2019 14:55
-
-
Save born2net/0a8e47a80e1e09fe984f57763680dc86 to your computer and use it in GitHub Desktop.
ngrx 8+ with immer and support for on() within reducer
This file contains hidden or 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
Sorry @DavidTheProgrammer, @luchillo17
On<S>
was an internal type I declared to help me with the return type.Below is my code for ngrx
^11.0.1
and immer^8.0.1
.I wanted the reducer's state to autocomplete as if immer was not included in the project, I view the code as "dirty", open to suggestions!