Dispatch Action Payloads to Reducers

Share this video with your friends

Send Tweet

While action types allow you tell your reducer what action it should take, the payload is the data that your reducer will use to update the state. This lesson shows you how to pass an action payload along with your action type to update the state.

Fabian Dietenberger
Fabian Dietenberger
~ 7 years ago

To make it work I had to implement to Action interface.

import { Action } from '@ngrx/store';

export const HOUR = 'HOUR';
export const SECOND = 'SECOND';

export class ClockAction implements Action {
  type: string;
  constructor(public payload: number) {
  }
}

export function clock(state: Date = new Date(), action: ClockAction): Date {
  const date = new Date(state.getTime());

  switch (action.type) {
    case SECOND:
      date.setSeconds(date.getSeconds() + action.payload);
      break;
    case HOUR:
      date.setHours(date.getHours() + action.payload);
      break;
  }

  return date;
}
Hugo
Hugo
~ 7 years ago

Thanks Fabian