Alex's Notes

Redux Middleware

As discussed in Redux: Tyler McGinnis

We can intercept a dispatch and handle it simply like this:

  function checkAndDispatch(store, action) {

    if ( action.type === ADD_TODO &&
	 action.todo.name.toLowerCase().indexOf('bitcoin') !== -1
       ) {
	   return alert("Don't do it!")
	 }
    return store.dispatch(action)
}

But this seems hacky. Instead we can use Redux middleware.

Middleware provides a third party extension point between dispatching an action and when it hits the reducer.

Why is this useful? We can use it for logging, error reporting, validation, routing.

We can define a function that takes a redux store as a parameter, and returns a function that takes a next parameter (the next in the line of middleware), ending in dispatch.

That function must itself return a function, that takes as input an action.

function checker(store) {

  return function(next) {
    return function(action) {
      //actual middleware code
      if (!valid) {
	return alert("not valid!");
      }
      return next(action)
    }
  }
}

// or in ES6
const checker = (store) => (next) => (action) => {
    //body of the middleware
}

Then when we create the store, we add the middleware like this:

const store = Redux.createStore(Redux.combineReducers({...}),
		   Redux.applyMiddleware(checker, logger));

There are lots of useful redux middleware packages like this:

https://github.com/evgenyrodionov/redux-logger: Redux middleware for calling an API.

https://github.com/pburtchaell/redux-promise-middleware: Redux middleware for resolving and rejecting promises with conditional optimistic updates.

https://github.com/gaearon/redux-thunk: Thunk middleware for Redux.

https://github.com/jeffbski/redux-logic: Redux middleware for organizing business logic and action side effects.

https://github.com/redux-observable/redux-observable: RxJS middleware for action side effects in Redux using Epics.

https://github.com/conorhastings/redux-test-recorder: Redux middleware to automatically generate tests for reducers through ui interaction.

https://github.com/ezekielchentnik/redux-reporter: Report actions and metadata to 3rd party providers, extremely useful for analytics and error handling (New Relic, Sentry, Adobe DTM, Keen, etc.)

https://github.com/elgerlambert/redux-localstorage: Store enhancer that syncs (a subset) of your Redux store state to localStorage.

https://github.com/low-ghost/redux-node-logger: A Redux Logger for Node Environments

https://github.com/sergiodxa/redux-catch: Error catcher middleware

https://github.com/grofers/redux-cookies-middleware/: a Redux middleware which syncs a subset of your Redux store state with cookies.

https://github.com/conorhastings/redux-test-recorder: Redux test recorder is a redux middleware + included component for automagically generating tests for your reducers based on the actions in your app

Links to this note