Applying Middleware to the Redux Store
Now that we have a custom middleware function, let's see how we can apply it to the Redux store. Applying middleware to the store allows us to intercept and modify actions before they reach the reducer.
To apply middleware to the store, we can use the applyMiddleware
function from the redux
library. This function takes one or more middleware functions as arguments and returns a store enhancer that can be used when creating the store.
Here is an example of applying the loggerMiddleware
to the store using the applyMiddleware
function:
1const store = createStore(reducer, applyMiddleware(loggerMiddleware));
In this example, we pass loggerMiddleware
as an argument to applyMiddleware
and then pass the resulting store enhancer to the createStore
function.
Now, when actions are dispatched to the store, the loggerMiddleware
will intercept them and log information about the dispatched action and the new state of the store.
Let's try running the following code snippet to see how the loggerMiddleware
works:
1const store = createStore(reducer, applyMiddleware(loggerMiddleware));
2
3store.dispatch({ type: 'INCREMENT' });
xxxxxxxxxx
const loggerMiddleware = store => next => action => {
console.log('Dispatching:', action);
const result = next(action);
console.log('New State:', store.getState());
return result;
};
const store = createStore(reducer, applyMiddleware(loggerMiddleware));