Reputation: 606
import { State, Action, StateContext } from '@ngxs/store';
export class FeedAnimals {
static readonly type = '[Zoo] FeedAnimals';
}
export interface ZooStateModel {
feed: boolean;
}
@State<ZooStateModel>({
name: 'zoo',
defaults: {
feed: false
}
})
export class ZooState {
@Action(FeedAnimals)
feedAnimals(ctx: StateContext<ZooStateModel>) {
const state = ctx.getState();
ctx.setState({
...state,
feed: !state.feed
});
}
}
I am learning ngxs from gitbook, above block copied from there.
In this exmaple ...state
assigned to object. why we need this? so we have only one object property feed and have already assigned feed: !state.feed
Upvotes: 0
Views: 313
Reputation: 20092
You need to use ...state because you want to modify the state of the current state
Using spread operator you are making copy operation so the previous state will be copy to the new state object and you modify the data in the new created state object.
const a = [1, 2, 3]
const b = [...a, 4, 5, 6] => [1, 2, 3, 4, 5, 6]
So this code
...state,
feed: !state.feed
You are making the new copy of the state object and modify the feed property inside your state object
Upvotes: 1