Managing State in Angular Apps with ngrx/store and ngrx/effects (Part 1)
Recently I released a new state management pattern. You should check it out.
This post assumes that you at least have some working knowledge of Angular, Rx and Redux.
In this article, we will learn how to create the traditional todo app with ngrx/store and ngrx/effects. The same concept will apply to @angular-redux/store with redux-observable.
In this part, we are going to focus on the todo’s implementation. Let’s see our component tree.
Build the Todo Component
The todo
component is just a dumb component that takes a todo as Input
and renders its title.
Build the Todos Component
The todos
component is also a dumb component that takes an array of todos and ngFor
over them to render the todo
component. There is also a loading indicator and error handling based on the state from our store.
Build the Todos Reducer
We are going to create all the actions in the same file; I don’t want to focus on how to structure your app.
I will not explain the reducer because it should be straightforward to you if you know Redux. (and if you’re reading this article, I hope you do)
Let’s register the reducer in our store:
Now we need to fetch the todos from the server, so let’s create a service that will manage this.
Build the Todos Service
We are just faking an HTTP request with the timer
operator from Rx and returning dummy data.
In Redux, reducers need to be pure so we need a middleware to handle our side effects. This will be the responsibility of ngrx/effects.
Build the Todos Effects
It looks difficult, but let's break it down.
We’re using the Effects
decorator to label our property getTodos$
as an effect
that will be triggered when we dispatch actions with the store.
@ngrx/effects exports an Actions
observable service that emits every action dispatched in your application.
The ofType
operator is for filtering actions by action type. In our case, we want to continue our effect process only if the action type is GET_TODOS
.
Every effect
need to return a new action, for example:
In our case the getTodos()
method returns an observable, so we need to merge the new action to our effect
stream with the help of the switchMap
operator.
When we dispatch the GET_TODOS
action the effect
will call the getTodos()
method to fetch the todos from the server and based on the response will return a new action.
Let’s register the TodoEffects
.
Now the final piece is to inject our store to the app component, dispatch GET_TODOS
action and get the todos from the store.
I will stop here because I don’t want the article to be long. In the next article, we will add the ability to add/toggle todo and after this the visibility filters.