Search code examples
angularngrxngrx-store

Avoid if statement NgRx Store


I want to get a state object inside a component I have created in Angular. However always the value is not loaded properly and undefined. Why is this going wrong? If I use the if statement the method is working fine but I don't get why it's going wrong. How can I load this properly?

const initialState: any = {
  id: 'campaignID1',
  name: 'Campagne 1'
};

export function reducer(state: Campaign = initialState, action: CampaignActions.Actions) {

  switch (action.type) {
    case CampaignActions.CHANGE_CAMPAIGN:
      return {
        id: action.payload.id,
        name: action.payload.name
      };
  }

}

campaign.reducer.ts

export const CHANGE_CAMPAIGN = '[Campaign] Change';

export class ChangeCampaign implements Action {
  readonly type = CHANGE_CAMPAIGN;

  constructor(public payload: Campaign) {
  }
}

export type Actions = ChangeCampaign;

campaign.action.ts

ngOnInit() {
    this.store.pipe(select('campaign')).subscribe(x => {
      if (x === undefined) { <------ THIS SHOULD BE UNNECESSARY
      } else {
        const params = new HttpParams()
          .set('campaignId', x.id);
        this.resourceService.list(params, '/campaign').subscribe(resources => {
          this.resources = resources;
        });
      }
    });
}

campaign.component.ts


Solution

  • This is happening because you are not returning the initial state in case of unknown action [or default]. You should return the initial state in case of default action. Change your reducer like this:

    export function reducer(state: Campaign = initialState, action: CampaignActions.Actions) {
    
      switch (action.type) {
        case CampaignActions.CHANGE_CAMPAIGN:
          return {
            id: action.payload.id,
            name: action.payload.name
          };
        default:
          return state;
      }
    
    }
    

    Hope it helps.