Middlewares And React Redux Life Cycle

rajaraodv
rajaraodv
Mar 10, 2016 · 4 min read

What are Middlewares?

Redux Life Cycle w/ And w/o Middlewares

Using Middlewares

npm install — save redux-promise
import React from ‘react’;
...
import { createStore, applyMiddleware } from ‘redux’;
import rp from ‘redux-promise’; // <------------ MIDDLEWARE
...
//add middlewares
const createStoreWithMiddleware = applyMiddleware(rp)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory} routes={routes} />
</Provider>
, document.getElementById(‘body’));

How does a Middleware Work?

//redux-promise middleware source codeimport { isFSA } from 'flux-standard-action';

function isPromise(val) {
return val && typeof val.then === 'function';
}

export default function promiseMiddleware({ dispatch }) {
return next => action => {
if (!isFSA(action)) {
return isPromise(action)
? action.then(dispatch)
: next(action);
}

return isPromise(action.payload)
? action.payload.then(
result => dispatch({ ...action, payload: result }),
error => dispatch({ ...action, payload: error, error: true })
)
: next(action);
};
}

Learn more:

My Other Blogs

ES6

WebPack

Draft.js

React And Redux :

Salesforce

rajaraodv

Written by

rajaraodv

Trying to make Web development simple. Former Developer Advocate @Salesforce, VMware (node.js); Engineer @ Yahoo, Zimbra. Twitter: @rajaraodv

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade