Create a gist now

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: 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