Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could I store object with its methods in @ngrx

I wanted to store objects with their methods with @ngrx/entity . Can it cause any problems in application? (Angular 2-7)

mission.class.ts:

import { v4 as uuid} from 'uuid';

export class Mission {

  id: string;
  title: string;
  completed: boolean;

  constructor (missionTitle: string, completed?: boolean) {
    this.id = uuid();
    this.title = missionTitle;
    this.completed = completed;
  }

  complete() {
    this.completed = true;
  }
}

There is the class with method 'complete' mission. I want to save it by @ngrx/entity.

missions.actions.ts:

export enum MissionActionTypes {
  AddMission = '[Mission] Add Mission'      
}

export class AddMission implements Action {
  readonly type = MissionActionTypes.AddMission;

  constructor (public payload: { mission: Mission }) {}
}

There is the action to add Mission object with its method to @ngrx/store

missions.reducer.ts:

export interface MissionsState extends EntityState <Mission> {

}

export const adapter: EntityAdapter <Mission> = createEntityAdapter<Mission>();

export const initialState: MissionsState = adapter.getInitialState();

export function reducer(state = initialState, actions: MissionActions) {

  switch (actions.type) {
  
    case MissionActionTypes.AddMission:
      return adapter.addOne(actions.payload.mission, state);
      
    default: 
      return state;
  }

}

When I fetch Mission object from the store using select() I can call 'complete' method of it. But I am Not sure if that approach will cause any problem in the application in the future..

like image 865
Itzhak Galitch Avatar asked Dec 04 '18 13:12

Itzhak Galitch


1 Answers

Yes it's possible, but this doesn't mean you should.

  • Actions should be serializable (methods are lost during serialization)
  • Selectors should be pure (it should not invoke a side effect, it should only read date from the state)
like image 188
timdeschryver Avatar answered Nov 07 '22 16:11

timdeschryver