Search code examples
angularngrxngrx-entity

How to create collection of EntityState in NGRX


Is it possible to create a State in NGRX like below?

export interface Invitation {
  id: string;
  sender: string;
  receiver: string;
}

export interface InvitationsState {
  invitations: { [key: string]: EntityState<Invitation> };
  loaded: boolean;
  error?: any;
}

I've created creating dynamic EntityState but unable to get it fully implemented.

Question: What will be an alternative way to model such store?

Got example of creating multiple Entities here, here which are pre-defined ones but not a dynamic one.


Solution

  • Here is the right strategy based on your requirement. Your state should be something like:

    entites: Account[],
    selectedAccount: Account,
    loading: Boolean,
    loaded: Boolean,
    error: String
    

    You account class should contain the department array within it. Below is a sample class.

    class Account{
    name: String,
    departments: Departments[]
    }
    

    Now, whenever you load accounts, you need to load the account and its child departments together. Next, when you click a particular account and go to view account details, you dispatch an action to select that specific account. This will provide you the specific account object and you can render it easily.

    I hope you will be able to figure out the corresponding effects and reducers. Feel free to ask for help if you need.