Skip to content

Instantly share code, notes, and snippets.

@shubhnik
Last active October 29, 2017 18:53
Show Gist options
  • Save shubhnik/24060249d6e658bd2f4497c3839e994a to your computer and use it in GitHub Desktop.
Save shubhnik/24060249d6e658bd2f4497c3839e994a to your computer and use it in GitHub Desktop.
Redux's "applyMiddleware" and "compose" utilities.
// ******************************************** applyMiddleware ********************************************
// Each code line is precedeed by its explanation.
// applyMiddlewrae function receives any number of middlewares. It is called while initiating a store.
function applyMiddleware(...middlewares) {
// returns a function which accepts the "createStore" function of redux. This function in turn, returns another function
// which accepts arguments reducer and preloadeState as in (..args).
return (createStore) => (...args) => {
// "createStore" returns an object which contains the wanted utilities "dispatch" and "getState"
const store = createStore(...args)
let dispatch = store.dispatch
let chain = []
const middlewareAPI = {
getState: store.getState,
dispatch: (...args) => dispatch(...args)
}
// returns an array of functions of that accepts the dispatch method wrapped by the previous middleware as a parameter( named next in dummyMiddleware in the bottom)
chain = middlewares.map(middleware => middleware(middlewareAPI))
//returns a function which accepts the action and do its thing with the action
dispatch = compose(...chain)(store.dispatch)
// Returns the store but with the wrapped disaptch method overriding the default redux store's dispatch method.
return {
...store,
dispatch
}
}
}
// ************************************************* compose ***********************************************
function compose(...funcs) {
if (funcs.length === 0) {
return arg => arg
}
if (funcs.length === 1) {
return funcs[0]
}
return funcs.reduce((a, b) => (...args) => a(b(...args)))
}
// ****************** A simple nonsense middleware that delays the action to dispatch by 5 seconds **********************
dummyMiddleware = store => next => action => {
setTimeout(() => next(action), 5000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment