Thursday, May 17, 2018

How to create and register a React redux middleware?

Overview


This post is just a reminder how to create and register a custom redux middleware.

Redux middleware: definition.

The middleware class

const middleware = function f1(store) { 

    return function f2(next) {
        
        return function f3(action) {
        
            // Do nothing but trace the action 
            console.log(`MIDDLEWARE> action:${JSON.stringify(action)}`)
            return next(action);
        } 
    }
}

export default middleware ;

The store creation and middleware registration

import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import thunkMiddleware  from 'redux-thunk';

import counterReducer   from './counter/counterReducer';

import middleware   from './middleware';

const rootReducer = combineReducers({
    counter : counterReducer,
});

const appliedMiddleware = applyMiddleware(thunkMiddleware, middleware);
const store             = createStore(rootReducer, {}, appliedMiddleware);

store.subscribe(function() {
    //console.log('STORE SUBSCRIBED ');
} );

export default store;

No comments:

Post a Comment