angularangular6angular7ngxsangular-state-managmement

Deleting an object in Angular NGXS


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);
  }

Solution

  • 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.