javascriptangularngrxngrx-storengrx-entity

Select and update the additional property of NgRx entity using component store


I have the below additional property

export interface MetricCreateState extends EntityState<UserSelectionListDto> {
    isLoading: boolean | undefined,
    isCreated: boolean | undefined,
    LoadConfigureMetric: boolean | undefined
}

Created a adaptor and initial property

export const adapter = createEntityAdapter<UserSelectionListDto>();
export const { selectAll, selectEntities } = adapter.getSelectors();

export const initialState: MetricCreateState = adapter.getInitialState({
    isLoading: false,
    isCreated: false,
    LoadConfigureMetric: false
});

I have a effect which load the data from the server side as

readonly getMetricOwners = this.effect((owners$: Observable<UserSelectionListDtoPagedResultDto>) => {
        this.setState((state) => adapter.setAll([], { ...state, isLoading: true }));
        return owners$.pipe(() => this.userServiceProxy.getUsersForSelection(undefined, undefined, undefined, undefined, undefined).pipe(
            tap({
                next: (owners) => {
                    this.setState((state) => adapter.setAll(owners.items, { ...state, isLoading: false }));
                },
                error: (e) => {
                    this.setIsLoading(false);
                },
            }),
            catchError(() => EMPTY),
        ));
    });

Over here I am trying to update the single property

this.setState((state) => adapter.setAll([], { ...state, isLoading: true }));

Is this is the correct way to set the additional property of the entity? and how do we select the particular additioanl property. For example


Solution

  • Not really, setAll also updates the entities collection

    Replace current collection with provided collection - docs

    If you just want to update isLoading, you don't need to adapter because the adapter only handles the entities.

    To update isLoading, you can simply do the following

    { ...state, isLoading: true }
    

    or use the patch method of ngrx component store

      this.componentStore.patchState({isLoading: true});