0

I have a problem deleting a comment on my post. How would you do it? I'm using the Angular NGXS state management. Pls see this link

CLICK THIS LINK

 onDeleteComment(commentId: number){
    this.store.dispatch(new DeleteComment(commentId));
 }



    @Action(DeleteComment)
  deleteComment(
    ctx: StateContext<PostStateModel>,
    { commentId }: DeleteComment
  ) {
    const state = ctx.getState();
    const filteredArray = state.post.comments.find(
      item => item.id === commentId
    );
    console.log(filteredArray);
  }
Richard.Davenport
  • 1,453
  • 3
  • 16
  • 31
Joseph
  • 7,042
  • 23
  • 83
  • 181

1 Answers1

1

Joseph, it looks like you've asked a few different question all relating to this same issue. I'd suggest you jump on the NGXS slack channel and ask more questions there: slack link.

But to answer your question.... You have a few fundamental issues with your state object, but those aside you should be able to just set/patch your state:

@Action(DeleteComment)
deleteComment(
  ctx: StateContext<PostStateModel>,
  { commentId }: DeleteComment
) {
  const state = ctx.getState();
  ctx.patchState({
    post: {
      ...state.post,
      comments: state.post.comments.filter(
        comment => comment.id !== commentId
      )
    }
  });
}

Here is an updated stackblitz

One thing to note, in the stackblitz example I updated angular dependencies to the latest version... Shouldn't have any effect on the action handler (reducer), it should still work.

Richard.Davenport
  • 1,453
  • 3
  • 16
  • 31
  • 1
    Richard's answer is spot on, but you can also use the built in NGXS state operators (in this case `remove`) to delete an item - see the documentation [here](https://www.ngxs.io/advanced/operators#supplied-state-operators) – Garth Mason Nov 24 '19 at 23:46