1

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.

hofshteyn
  • 1,272
  • 4
  • 16
  • 33

2 Answers2

2

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

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

    constructor() {
        weight = 0.2;
    }
}
  • and when I want to change weight will it keep my new value in store? – hofshteyn Jan 22 '19 at 12:16
  • Of course. The initial weight gets only set once at construction time. Whatever value you put in afterwards will be kept as current value. –  Jan 22 '19 at 12:18
0

You shouldn't add classes in the storage to keep it serializable, ok your potato is but it is tempting to add functions there now that it exists and then it isn't anymore.

I'd use factory function for creating a Potato instead.

interface Potato {
  id: number;
  weight: number;
}

const createPotato = (potato: Potato = { id: undefined, weight: 0.2 }) => potato;

console.log(createPotato());
console.log(createPotato({id: 20, weight: 300}));

MTJ
  • 1,059
  • 1
  • 10
  • 23