Implementing a Meta-Reducer in ngrx/store
You don’t really need middleware
The ngrx team decided that we don’t need middleware anymore, in most cases, we can use meta-reducers to achieve the same effects.
What is a meta-reducer?
A meta-reducer is just a fancy name for higher order reducer (i.e., function).
Because a reducer is just a function, we can implement higher order reducer — “meta reducer.”
higher order function is a function that may receive a function as parameter or even return a function.
In simple words —
Take a reducer, do what you need and return a new reducer.
Create Logger Meta-Reducer
This is the basic signature of meta-reducer. The function expects to get a reducer function and needs to return a new reducer.
The logger
reducer is just logging the current state, the action, and the next state then we returning the results of the current reducer function (combineReducers
) without any modification.
Now let’s see how we can add the meta-reducer to our store.
First we need to pass the reducers
to the combineReducers
function. As you may know, the combineReducers
will return a new reducer that will call every child reducer, and gathers their results into a single state object.
With the help of the compose
function we can take the combineReducers
result ( the new reducer ) and pass it to the logger
meta-reducer.
If we simplify the compose
function we will get the following code:
Now let’s see another example. Reset the state when the user logs out.
Create Reset Meta-Reducer
We need to clear the store after the LOG_OUT
action.
If the action type is LOG_OUT
we will return an undefined
state and therefore all of the reducers will return the initial value as they are supposed to.
Now we can add the reset
meta-reducer to our store.