Last active
September 10, 2017 23:22
-
-
Save bushidocodes/6771920849410e5b2ed142a204cacc5f to your computer and use it in GitHub Desktop.
Basic reimplementation of promise middleware for Redux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// middlewares/async.js | |
export default function({ dispatch }) { | |
return next => action => { | |
// Check if a thenable | |
if (action.payload.then) { | |
// If a thenable, don't call next until the promsie resolves | |
action.payload = action.payload.then(res => { | |
action = { ...action, payload: res.data }; | |
next(action); | |
}); | |
} else { | |
// Otherwise resolve immediately | |
next(action); | |
} | |
}; | |
} | |
// index.js | |
import React from "react"; | |
import ReactDOM from "react-dom"; | |
import { Provider } from "react-redux"; | |
import { createStore, applyMiddleware } from "redux"; | |
import Async from "./middlewares/async"; | |
import App from "./components/app"; | |
import reducers from "./reducers"; | |
const createStoreWithMiddleware = applyMiddleware(Async)(createStore); | |
ReactDOM.render( | |
<Provider store={createStoreWithMiddleware(reducers)}> | |
<App /> | |
</Provider>, | |
document.querySelector(".container") | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment