0

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?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

1 Answers1

1

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

timdeschryver
  • 14,415
  • 1
  • 19
  • 32
  • I have been reading about normalising state and normalizr ... By using this approach shouldn't I use a global state instead of a state per page? Imagine I have two pages, one displays recent posts with tags and the second top posts without tags. But both would use the global state where Posts and Tags entities exist in a normalised state. Or should I keep having a specific state per page? – Miguel Moura Jun 15 '20 at 23:28
  • 1
    You will have 1 global state, and multiple selectors that compose a "viewmodel" for your pages. – timdeschryver Jun 16 '20 at 07:24