Immer adapter

Declarative state mutations

Build Status Build status NPM License Codacy Badge Greenkeeper badge

📦 Install

To install @ngxs-labs/immer-adapter and immer that is a peer-dependency run the following command:

npm install @ngxs-labs/immer-adapter immer --save
# or if you use yarn
yarn add @ngxs-labs/immer-adapter immer

Before

When your state is growing - it becomes harder to manage such mutations:

import { State, Action, StateContext } from '@ngxs/store';
import { Receiver, EmitterAction } from '@ngxs-labs/emitter';
export class FeedZebra {
public static readonly type = '[Animals] Feed zebra';
constructor(public payload: string) {}
}
@State<AnimalsStateModel>({
name: 'animals',
defaults: {
zebra: {
food: [],
name: 'zebra'
},
panda: {
food: [],
name: 'panda'
}
}
})
export class AnimalState {
@Action(FeedZebra)
public feedZebra({ getState, setState }: StateContext<AnimalsStateModel>, { payload }: FeedZebra) {
const state = getState();
setState({
...state,
zebra: {
...state.zebra,
food: [...state.zebra.food, payload]
}
});
}
// OR if you are using ER approach
@Receiver()
public static feedZebra({ getState, setState }: StateContext<AnimalsStateModel>, { payload }: EmitterAction<string>) {
const state = getState();
setState({
...state,
zebra: {
...state.zebra,
food: [...state.zebra.food, payload]
}
});
}
}

After

immer-adapter gives you the opportunity to manage mutations in a more declarative way:

import { State, Action, StateContext } from '@ngxs/store';
import { Receiver, EmitterAction } from '@ngxs-labs/emitter';
import { produce } from '@ngxs-labs/immer-adapter';
export class FeedZebra {
public static readonly type = '[Animals] Feed zebra';
constructor(public payload: string) {}
}
@State<AnimalsStateModel>({
name: 'animals',
defaults: {
zebra: {
food: [],
name: 'zebra'
},
panda: {
food: [],
name: 'panda'
}
}
})
export class AnimalState {
@Action(FeedZebra)
public feedZebra(ctx: StateContext<AnimalsStateModel>, { payload }: FeedZebra) {
produce(ctx, (draft: AnimalsStateModel) => draft.zebra.food.push(payload));
}
// OR if you are using ER approach
@Receiver()
public static feedZebra(ctx: StateContext<AnimalsStateModel>, { payload }: EmitterAction<string>) {
produce(ctx, (draft: AnimalsStateModel) => draft.zebra.food.push(payload));
}
}