Redux ~ Middleware - rohit120582sharma/Documentation GitHub Wiki

It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, and more.


Middleware functions

The middleware is a curried function. A curried function is a function that returns another function.

Our middleware receives a store, which is expected to return a function that accepts the next function, which is expected to return a function which accepts an action.

  • The Store: That’s our redux store.
  • The Next: We call this function when our middleware is done with the task assigned to do. This sends our actions to our reducer or another middleware.
  • The Action: Thats our action currently being dispatched.

In our middleware we have access to store.getState() to get the current state and store.dispatch() to dispatch a new action if we want to.

const loggingMiddleware = (store)=>{
	// Called when calling applyMiddleware so our middleware can have access to the store
	return (next)=>{
		// next is the following action to be run after this middleware
		return (action)=>{
			// finally, this is where our logic lives for our middleware.
			return next(action);
		}
	}
}

applyMiddleware

In order to apply middleware to our stack, we'll use this aptly named applyMiddleware function as the second argument to the createStore() method.

import { createStore, applyMiddleware } from 'redux';
...
const store = createStore(rootReducer, applyMiddleware(loggingMiddleware));


⚠️ **GitHub.com Fallback** ⚠️