I need an alternative to change the same attribute, with the same value, for all items in an array in Ngxs.
I tried to use updateItem(() => true, patch({ ... })), but it doesn't work because the first function, () => true, just returns the first match and ends up updating only a single item.
The following is a simplified example of what I tried to do:
import { State, Action, StateContext } from '@ngxs/store';
import { patch, append, removeItem, insertItem, updateItem } from '@ngxs/store/operators';
export interface AnimalsStateModel {
others: { /*...*/ }[];
rabbits: Rabbit[];
}
export interface Rabbit {
name: string,
alive: boolean,
}
export class ChangeRabbitAlive {
static readonly type = '[Animals] Change rabbit alive';
constructor(public payload: { name: string; alive: boolean }) {}
}
export class ChangeAllRabbitsDead {
static readonly type = '[Animals] Change all rabbits dead';
constructor(public payload: { }) {}
}
@State<AnimalsStateModel>({
name: 'animals',
defaults: {
others: [ /*...*/ ],
rabbits: [
{ name: 'Michael', alive: true },
{ name: 'John', alive: true },
{ name: 'Jimmy', alive: true },
{ name: 'Jake', alive: true },
{ name: 'Alan', alive: true },
]
}
})
export class AnimalsState {
@Action(ChangeRabbitAlive)
changeRabbitAlive(ctx: StateContext<AnimalsStateModel>, { payload }: ChangeRabbitAlive) {
ctx.setState(
patch({
rabbits: updateItem<Rabbit>(rabbit => rabbit.name === payload.name, patch({ alive: payload.alive }))
})
);
}
@Action(ChangeAllRabbitsDead)
changeAllRabbitsDead(ctx: StateContext<AnimalsStateModel>, { payload }: ChangeAllRabbitsDead) {
const isAlive = { alive: false };
ctx.setState(
patch({
//rabbits: updateItem<Rabbit>(name => true, patch({ alive: false }))// Type 'boolean' is not assignable to type 'false'
rabbits: updateItem<Rabbit>(() => true, patch(isAlive))
})
);
}
}
Is there any way to kill all the rabbits at once?
Extra: If you could explain why the error "Type 'boolean' is not assignable to type 'false'" occurs in that situation, that would also be appreciated.