Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Thunk Middleware with Custom API Utils
// Now your action creators can pull utilities our of their thunk api!
export function fetchUser(id) {
return ({api, dispatch}) =>
api.fetch(`users/${id}`).then(resp =>
dispatch({action: FETCH_USER, user:}));
// And now testing is *super* easy - just inject away!
it ('should hit correct endpoint', () => {
const api = createMockApi([
{test: 'users/1', resp: ({data: {id: 1, type: 'user', name: 'Chris'}})}
const store = createMockAppStore({api});
{action: FETCH_USER, user: {id: 1, type: 'user', name: 'Chris'}}
// setup middleware with whatever we want to inject via a thunk args interface
const args = {};
const thunkMiddleware = createThunkMiddleware(args);
args.api = api;
args.getState = store.getState;
args.dispatch = store.dispatch;
// Where the magic happens
export function createThunkMiddleware(args) {
return function createDispatch(next) {
return function doDispatch(action) {
if (isFunction(action)) {
return doDispatch(action(args));
return next(action);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment