2

I had a problem while trying NGXS state management, the problem is if I delete the record from the array using id, then the entire array getting empty. this is 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",
      }
    ],
  },
})

and this is how delete action looks like

 @Action(DeleteUser)
  delete(
    { getState, patchState, setState }: StateContext<UserStateModel>,
    { id }
  ) {
    const state = getState();

    setState(
      patch({
        users: state.users.filter((user) => {
          user.id !== id;
        }),
      })
    );
  }

this is how I dispatch the action in 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));
  }
}
Raheem Mohamed
  • 789
  • 3
  • 6
  • 15

1 Answers1

3

After several hours of trying finally found the solution and resolved the issue. first,click here to go through NGXS state operator official documentation.

"removeItem" operator is a solution to this problem.

import {
  patch,
  removeItem
} from "@ngxs/store/operators";

export class UserState {
    @Action(DeleteUser)
          delete(
            { getState, patchState, setState }: StateContext<UserStateModel>,
            { id }
          ) {
            const state = getState();
        
            setState(
              patch({
                users: removeItem<User>((user) => user.id === id),
              })
            );
          }
    }

Hope this will helpful.

Raheem Mohamed
  • 789
  • 3
  • 6
  • 15