Dispatch Action Payloads to Reducers

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated a year ago

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.

[00:00] Now that we've extracted out our types of hour and second, the next thing I want to work on are these hard coded plus ones, which I want to extract so that I can pass them in and change that if I want.

[00:12] I'm going to move this plus one up into this object that comes in and call it "payload." Instead of plus one, I'll say payload, and same thing here, I'll say payload.

[00:27] Now in my app, I need to pass a payload along, so we'll start by hard coding it. We'll hard code that to just one. Now when I refresh, we'll have this same behavior of it incrementing by one second, and when I click, it's incrementing by the hour.

[00:45] What I want to do is move this one up even further into here where I map to something that has a one. Instead of mapping to just hour, I'm going to map to an object, where the type is hour, and the payload is one. Then here I'm going to map to an object where the type is second and the payload is one.

[01:14] That way, this object that comes through, instead of just being a type, I'm going to call it an "action." I can delete this entire object there, and we'll just call that the action. That way, we've extracted everything that came through before, and it's being passed as an object with both the type and payload and a type and a payload.

[01:34] Now when I refresh, you can see I'll have the same exact behavior, one second and one hour. I could also change it so that when I click, I would update by four hours and every second it would update by three seconds.

[01:52] That's now configurable, so whenever I refresh, you can see three seconds, three seconds, four hours.

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

Markdown supported.
Become a member to join the discussionEnroll Today