Ищите примеры для погружения в продукт с помощью ngrx 8 - PullRequest
0 голосов
/ 10 июля 2019

Посмотрел в Интернете и не могу найти пример использования import produce, {Draft} from "immer"; с ngrx on(). Самое близкое, что я могу найти: неполное решение по: https://github.com/immerjs/immer/issues/252

import produce, { Draft } from 'immer';
import { ActionCreator, createReducer, on } from '@ngrx/store';
import { ActionType, FunctionWithParametersType } from '@ngrx/store/src/models';

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)));
}

// Usage:

const featureReducer = createReducer(
  initialState,
  produceOn(action, (draft, action) => {
     // TODO STUFF
  }
);

export function reducer(state = initialState, action) {
  return featureReducer(state, action);
}

не знаю, как отключить функцию on () с помощью immer с помощью ngrx 8

Sean.

1 Ответ

0 голосов
/ 10 июля 2019

нашел ответ:

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...');
    })
);
...