angularangular6angular7ngxsangular-state-managmement

Deleting an object of a nested data in Angular using NGXS


I have successfully implemented the get and delete function of post in my Angular app. My problem comes when you wanted to delete a comment inside a post. I'm trying to achieve it using NGXS. How will i be able to access it inside of the post so i can retrieve the comment to be able to delete it. Here's what i have done

SEE THIS LINK

CODE

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



 @Action(DeleteComment)
  deleteComment(
    { getState, setState }: StateContext<PostStateModel>,
    { id }: DeleteComment
  ) {
    const state = getState();
    const filteredArray = state.posts.filter(item => item.id !== id);
    setState({
      ...state,
      posts: filteredArray
    });
  }

Solution

  • In order to delete the comment from a post you'd have to first specify from which post you'd like to remove the comment:

    // app.component.ts
    onDeleteComment(postId: number, commentId: number){
      this.store.dispatch(new DeleteComment(postId, commentId));
    }
    

    Next step is to update your DeleteComment action to accept new parameter:

    // post.action.ts
    constructor(public readonly postId: number, public readonly commentId: number) { }
    

    And lastly, update your state with the help of ngxs's state operators (patch, updateItem, removeItem):

    @Action(DeleteComment)
    deleteComment(
      { getState, setState }: StateContext<PostStateModel>,
      { postId, commentId }: DeleteComment
    ) {
      const state = getState();
    
      setState(patch<PostStateModel>({
        // firstly, you're modifying the post by removing a comment from it
        posts: updateItem<Post>(p => p.id === postId, patch<Post>({
          // secondly, you remove the comment itself
          comments: removeItem<Comment>(c => c.id === commentId)
        }))
      }));
    }
    

    Here is a link to updated stackblitz