State Management: Action and Reducer

Now that we’ve covered what’s the global State and what’s the Store service, let’s take a look at how we can update that State. In our introduction to state management, we introduced Actions.

Actions are simple objects with a name/type describing what we’re trying to do. An optional payload contains the parameters for that Action. In our example of currency switcher, we want to change a currency, so we would create the following Action, where the payload is the new currency:

The above Action does absolutely nothing on its own. We need a reducer to implement the corresponding state transition. With NgXs, a reducer is a method with the decorator @Action in our State class:

In the above code, we define which method runs when the Action of type ChangeCurrency is dispatched to our state management library.

That method takes the current State, creates a copy of it (this is a core principle of Redux), and then changes the currency and exchangeRate in the new state object.

Then, NgXs will automatically notify any component/service/directive subscribed to that State that a new value has been set.

How to dispatch an action?

If we want to use the Action and Reducer created earlier, we use the only object that knows about everything in our state-management machinery: The Store.

Conveniently enough, our Store has a dispatch method that can be used for any Action:

As a reminder, the Store is a service that can be injected anywhere we need it:

We’ve covered most of the pieces of our state management architecture. We know how to create a State, an Action, a Reducer and use the Store to dispatch an action and update our State:

In our next post in this series, we’ll see how to Select and subscribe to specific parts of our State. You can see that example in action on Stackblitz.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.