Chapter 5: Actions
#
What are Actions?Actions
are the most simple core concept of NgRx (and Redux in general). Action is a unique event that is used to trigger a change in the state. What does it mean? For example, we might have an action that says "Home page has been loaded". It might mean some changes in the state. For example, in our application, it might trigger an API call for lists of expenses and incomes, which will in turn trigger an event that puts that data in the Store
, resulting in a change in the UI. Or we might have an action that says "Add a category", which will create a new category of income/expense in the Store
, again resulting in a UI change. Again, essentially Actions
are like commands to the Store
, or methods that allow to update its contents.
#
What does an Action look like?Actions are simple. An action is usually an object with just two properties: a type
, a string that indicates what exactly that action represents, and an optional payload
that is kind of like a function argument. In our example, an action that adds a category might look like this:
const addCategoryAction = { type: "[Categories List] Add Category", payload: { name: "Food" },};
This is an action that adds a category named Food
to the list of all categories. Of course, we still haven't written the logic that actually uses this action to put the data in the store, but for now we are focusing on the Actions
.
#
Creating an actionNgRx provides some utility functions to help us create actions instead of creating our objects by hand as we did in the previous example.
To start learning about those, let's create a folder names state
in the src/app
directory, and a file called actions.ts
inside it.
createAction
#
Using The first way of doing so is by using createAction
which will create a single action given the name and the parameters provided:
import { createAction, props } from "@ngrx/store";import { Category } from "./state";
export const addCategory = createAction( "[Category List] Add Category", props<{ category: Category }>());
Let's break down this example. First of all, the name createAction
is a bit deceptive; it does not create an action; in fact, it creates a function which, when called, will produce an action object. The first argument is the type
of the action that will be produced. When called, the addCategory
function will always create an action with type "[Category List] Create Category". The second argument uses the bizarre function props
, which is a generic function that allows us to define the type of the payload
which the created action will have. Essentially, it explains that in order to create the action using the addCategory
function, we should call it and provide an object that has a property category
which is defined in the Interface Category defined in the AppState. Let's do this and console.log
the result.
import { Component, OnInit } from "@angular/core";import { addCategory } from "./state/actions";
@Component({/* ... */})export class AppComponent implements OnInit { ngOnInit() { console.log(addCategory({category:{ name: "Food" }})); }}
In the console, we will see the following:
{ type: "[Category List] Add Category", category: { name: "Food" }}
So essentially, createAction
provided us with an easy way of creating a single action. addCategory
in our case is an ActionCreator
, a function which produces an action object whenever called, and props
explained what argument that ActionCreator
function expects.
createActionGroup
#
Using As we just saw, creating an action is pretty straightforward.
However, when dealing with multiple actions, this can lead to a more verbose code and prone to typos:
export const addCategory = createAction( "[Category List] Add Category", props<{ category: Category }>());
export const addAnotherCategory = createAction( // ๐ Did you notice the typo? "[Catgory List] Add Another Category", props<{ category: Category }>());
With those issues in mind, NgRx published a new function that allows us to create multiple actions at one: the createActionGroup
function.
Its usage is fairly simple and is based on two parameters:
- The source of the action, in our case
Category List
- A series of properties symbolizing our actions and their parameters
Let's go back to the previous example to see what is changing:
export const categoryActions = createActionGroup({ source: 'Category List', events: { 'Add Category': props<{ category: Category }>(), 'Add Another Category': props<{ category: Category }>(), }})
By doing so, all our related actions will be grouped together and we still can create them by calling the categoryActions
variable that automatically generates you the code to create them:
categoryActions.addCategory({ category: 'Food' });categoryActions.addAnotherCategory({ category: 'Food' });
note
Notice that our action types like Add Category
written in plain English are converted to addCategory
- a camel case variable name. This magic is done using TypeScript's template literal types and the mapped types. The source code for this is pretty fascinating, if you're a TypeScript enthusiast, I strongly recommend checking it out or listen to. You can also listen to Brandon Robert's video about the "TypeScript magic" behind the scenes.
#
HomeworkYes, you've read it correctly: we have learned how to write some basic code in NgRx, so it is time for some homework!
info
We strongly recommand you not to move on to the next chapter without adding the homework code as we will be using that code in the next chapters
- Create an action for deleting a category It should receive a string with the name of the category, and in the next chapter we will use that code to write the actual logic for deleting the category.
- Create an action for updating a category
It must receive a
Category
object ({name: string}
), and again, we will write the code to update the category in the next chapter
For this homework, assume categories cannot have duplicate names. We will deal with this problem later.
note
You will find solution code for all the homeworks at the end of the chapters
In this chapter, we learned how to create Actions
, unique events that specify what should happen to the state. In the next one, we will be writing code that actually does the transformation in the state.
Exercise 1 solution
Using createActionGroup
:
export const categoryActions = createActionGroup({ source: 'Category List', events: { 'Add Category': props<{ category: Category }>(), 'Delete Category': props<{ category: Category }>(), }})
Using createAction
:
export const addCategory = createAction( "[Category List] Add Category", props<{ category: Category }>());
export const deleteCategory = createAction( "[Category List] Delete Category", props<{name: string}>());
Exercise 2 solution
Using createActionGroup
:
export const categoryActions = createActionGroup({ source: 'Category List', events: { 'Add Category': props<{ category: Category }>(), 'Delete Category': props<{ category: Category }>(), 'Update Category': props<{ category: Category }>(), }})
Using createAction
:
export const addCategory = createAction( "[Category List] Add Category", props<{ category: Category }>());
export const deleteCategory = createAction( "[Category List] Delete Category", props<{name: string}>());
export const updateCategory = createAction( "[Category List] Update Category", props<{ name: string }>());