Skip to content

Instantly share code, notes, and snippets.

@chrisui
Created April 11, 2016 19:22
Show Gist options
  • Save chrisui/750ee07f500df6355f2bcee96115b769 to your computer and use it in GitHub Desktop.
Save chrisui/750ee07f500df6355f2bcee96115b769 to your computer and use it in GitHub Desktop.
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: resp.body.data}));
}
// 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});
store.dispatch(fetchUser(1));
expect(api.fetch.firstCall.args[0]).toEqual('users/1');
expect(store.dispatch.firstCall.args[0]).toEqual(
{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