Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Add a Second Reducer to the Store

    John LindquistJohn Lindquist
    angularAngular
    2 - 6
    ngrx-store@ngrx/store
    rxjsRxJS
    5 - 6

    Stores can accept as many reducers as you need. This lesson covers adding a second reducer that will be used to control an array of people.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Now let's add some people to our application. We'll set up a people reducer. Over time, you'll get very familiar with this syntax. We have a state and a type and a payload. Then you switch based on that type. You'll always want to have a default that's going to return the state if the type didn't match anything. Just going to format this real quick.

    Let's go ahead and do the same thing up in our previous reducer. We have a default instead of falling through to returning the state. It doesn't really change anything, makes it more consistent that way. All of your reducers will start with this template of a function that has a state and an action.

    Then you switch on the action type, and by default, it returns a state. Then you'll set up all of these different types to switch on. The default for my people state is going to an array. I'm going to pull that out right here and call it default people.

    Then our people are going to have a name, start with Sarah, and a time. We'll start with an empty time. I'll duplicate these. Give us four people -- John, Nancy, and Drew. Now the default for this state can be our default people.

    To access this reducer, we come into our main. We grab people from the reducers. We pass it into this object here. Then in our app, our store now has access to the people's reducer. If we say people and this.people is store select people, then up in our template, we'll turn the clock back on.

    We'll have a div that does an NG for person of people. This is coming from the store, so this is asynchronous. Make sure to add that asynch pipe or it's not going to work. Then we'll see person.name is in person.time.

    Let's save. I'll refresh here. You can see now we have Sarah is in blank. John is in blank. That's because all of our reducers have times that are empty.