When I was working with NGXS state management, I encountered a problem where attempting to delete a record from the array by its ID resulted in the entire array becoming empty. Below is an example of what my user state looks like:
@State<UserStateModel>({
name: "users",
defaults: {
users: [
{
id: 179,
name: "test",
email: "test@gmail",
},{
id: 190,
name: "test12",
email: "test12@gmail",
}
],
},
})
Here is the delete action implementation:
@Action(DeleteUser)
delete(
{ getState, patchState, setState }: StateContext<UserStateModel>,
{ id }
) {
const state = getState();
setState(
patch({
users: state.users.filter((user) => {
user.id !== id;
}),
})
);
}
Below is how I trigger the delete action in my component:
export class IndexComponent implements OnInit {
// users: Observable<User>;
@Select(UserState.getUsers) users: Observable<User>;
constructor(private store: Store) {}
deleteUser(id: number) {
this.store.dispatch(new DeleteUser(id));
}
}