Declarative state mutations
npm install @ngxs-labs/immer-adapter immer --save
# or if you use yarn
yarn add @ngxs-labs/immer-adapter immer
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]
}
});
}
}
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));
}
}