Search code examples
angulartypescriptngrxngrx-entity

ngrx: set deafult value for entities


How can I set a deafult value for entities while initiate state in ngrx entities?

potato.model.ts

export class Potato {
    id: number;
    weight: number;
}

potato.reducer.ts

export interface PotatoState extends EntityState<Potato> { }

export const potatoAdapter: EntityAdapter<Potato> = createEntityAdapter<Potato>();

const potatoesInitialState: PotatoState = potatoAdapter.getInitialState();

export const initialState: State = {
    potatoes: potatoesInitialState
};

export function reducer(state = initialState, action: PotatoActions): State {
    switch (action.type) {
        // ...
    }
}

For example I need to set deafult weight 0.2.


Solution

  • I'd suggest you use the default-constructor for this:

    export class Potato {
        id: number;
        weight: number;
    
        constructor() {
            weight = 0.2;
        }
    }