ngrxngrx-storengrx-entity

How to add item to entities in initial state using ngrx


I am using entities and instead of having empty entities at the start I want to add a default item in the initial state. I tried something like below:

const id = uuidv4()

const zeroState = adapter.getInitialState({
  activeTabId: id,
});

const homeTab = {
  pageID: id,
  pageTitle: 'Home',
} as PageInfo;

export const initialState = adapter.addOne(homeTab, zeroState);

It works fine in dev environment and ng build --prod=true also builds fine. But when I deploy the application doesn't run/load anything and instead throws Uncaught Error: Cannot enable prod mode after platform setup..

Can someone tell me on how to add an item to initial entity state ?


Solution

  • Unfortunately adapter.addOne doesn't work so early. But there're some alternatives.

    You can inject your entity manually, the store structure of entities is quite simple:

    const id: any = uuidv4(); // any because of type cast.
    
    const zeroState = adapter.getInitialState({
        activeTabId: id,
    });
    
    export const initialState = {
        ...zeroState,
        ids: [
            ...zeroState.ids,
            id,
        ],
        entities: {
            ...zeroState.entities,
            [id]: {
                pageID: id,
                pageTitle: 'Home',
            },
        },
    };
    

    Or you can use an effect for that, it works in prod mode.

    @Injectable()
    export class EntitiesEffects {
        @Effect()
        public readonly data$ = this.actions$.pipe(
            ofType(ROOT_EFFECTS_INIT),
            switchMapTo(
                merge(
                    of(
                        new UpsertAddress({
                            address: {
                                id: 'address1',
                                name: 'Address 1',
                            },
                        }),
                        // more entities
                        new UpsertUser({
                            user: {
                                id: 'user5',
                                name: 'User 5',
                                companyId: 'company3',
                            },
                        }),
                        new UpsertUser({
                            user: {
                                id: 'user6',
                                name: 'User 6',
                                companyId: 'company3',
                                managerId: 'user5',
                            },
                        }),
                    ),
                ),
            ),
        );
    
        constructor(protected readonly actions$: Actions) {}
    }
    

    And then in AppModule

    @NgModule({
        imports: [
            EffectsModule.forRoot([EntitiesEffects]),
        ],
    })
    export class AppModule {}