Middleware
- Suggested way to extend Redux with custom functionality.
- Provides a third-party extension point between dispatching an action, and the moment it reaches the reducer.
- Use middleware for logging, crash reporting, performing asynchronous tasks etc.
We will use 'redux-logger' in this example.
Previous code
// index.js
const redux = require('redux')
const createStore = redux.createStore
const combineReducers = redux.combineReducers
const BUY_CAKE = 'BUY_CAKE';
const BUY_ICECREAM = 'BUY_ICECREAM';
//action creator
function buyCake() {
return {
type: BUY_CAKE,
info: 'First redux action'
}
}
function buyIceCream() {
return {
type: BUY_ICECREAM,
}
}
const initialCakeState = {
numOfCakes: 10,
}
const initialIceCreamState = {
numOfIceCreams: 20
}
const cakeReducer = (state = initialCakeState, action) => {
switch(action.type){
case BUY_CAKE: return {
...state,
numOfCakes: state.numOfCakes - 1
}
default: return state
}
}
const iceCreamReducer = (state = initialIceCreamState, action) => {
switch(action.type){
case BUY_ICECREAM: return {
...state,
numOfIceCreams: state.numOfIceCreams - 1
}
default: return state
}
}
const rootReducer = combineReducers({
cake: cakeReducer,
iceCream: iceCreamReducer
})
const store = createStore(rootReducer);
console.log("initial state : ", store.getState());
const unsubscribe = store.subscribe(() => console.log("updated state :", store.getState()));
store.dispatch(buyCake()); //action of buying a cake
store.dispatch(buyCake());
store.dispatch(buyCake());
store.dispatch(buyIceCream());
store.dispatch(buyIceCream());
unsubscribe();
1. In terminal, type following.
npm i --save redux-logger
2. Import the 'logger' middleware .
const redux = require('redux');
const reduxLogger = require('redux-logger'); //add this line
const createStore = redux.createStore;
const combineReducers = redux.combineReducers;
const logger = reduxLogger.createLogger(); //add this line
We now have the logger middleware we want to use in our application.
3. Include the middleware by adding this line.
'applyMiddleware' : used to apply middleware.
const redux = require('redux');
const reduxLogger = require('redux-logger');
const createStore = redux.createStore;
const combineReducers = redux.combineReducers;
const applyMiddleWare = redux.applyMiddleware; //add this line
const logger = reduxLogger.createLogger();
4. Pass in a second parameter to 'createStore'.
You can pass in as many middlewares that your application requires.
const rootReducer = combineReducers({
cake: cakeReducer,
iceCream: iceCreamReducer
})
//const store = createStore(rootReducer); //remove this line
const store = createStore(rootReducer, applyMiddleWare(logger)); //add this line
5. Remove the 'console.log' statement in the store subscription
as we have the logger middleware to handle all of that.
//remove this line
//const unsubscribe = store.subscribe(() => console.log("updated state :", store.getState()));
const unsubscribe = store.subscribe(() => {}); //add this line
9. Run the code by typing this in the terminal
node index //(name of the file)
Results.
The first 'Inital state' is logged by the code that we wrote.
Summary - How to use middlewawre in Redux
1. Import 'applyMiddleware'
2. Pass it as an argument to 'createStore()', and pass in the middleware to the 'applyMiddleware()' method.
Check out my Korean version of this posting !
This posting is a summary of the Youtube video 'React Redux Tutorial' by Codevolution.
Github repository - https://github.com/rocher71/redux-demo
This commit - https://github.com/rocher71/redux-demo/commit/031859203afd69a86eca2b6fd5cd185e587896b9