Skip to content

Instantly share code, notes, and snippets.

@bushidocodes
Last active September 10, 2017 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bushidocodes/6771920849410e5b2ed142a204cacc5f to your computer and use it in GitHub Desktop.
Save bushidocodes/6771920849410e5b2ed142a204cacc5f to your computer and use it in GitHub Desktop.
Basic reimplementation of promise middleware for Redux
// 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