rainversion_3
rainversion_3

Reputation: 967

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 ?

Upvotes: 2

Views: 2253

Answers (2)

Christian Jensen
Christian Jensen

Reputation: 965

Use the setAll method of your adapter:

const initialState = adapter.setAll([homeTab], zeroState);

(where homeTab is an entity and zeroState is the return value of adapter.getInitialState)

Upvotes: -1

satanTime
satanTime

Reputation: 13584

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 {}

Upvotes: 2

Related Questions