Search code examples
angularngrxangular9

Add item to state after updating in API call using NGRX


I am using NGRX/Entity with Angular 9 and I have the entities:

export interface Post {
  id: number;
  content: string;
  title: string;
  tags: Tag[];
} 

export interface Tag {
  id: number;
  name: string;
}

And the reducer is something like:

export interface State extends EntityState<Post> { }

export const adapter: EntityAdapter<Post> = createEntityAdapter<Post>();

export const initialState: State = adapter.getInitialState();

const postReducer = createReducer(
  initialState,
  on(PostActions.updatePost, (state, { post }) => {
    return adapter.updateOne(post, state)
  })

When updating a post the API accepts a model different from when getting:

export interface PostUpdateModel {
  id: number;
  content: string;
  title: string;
  tagsIds: number[];
}  

My idea would be to have an Effect that accepts a PostUpdateModel and sends it to the API which returns a Post and then call updateOne.

Does this make sense? How can I do this?


Solution

  • Yes, this makes sense. Another way at looking at it is to send the whole Post object to the effect and let the effect map it to a request object.

    Also, at the moment a collection of tags is stored for each post. This can be harder to maintain in more complex scenarios because this data is duplicated, normaling state can offer a solution to tackle this problem (if you have it).