Created
April 11, 2016 19:22
-
-
Save chrisui/750ee07f500df6355f2bcee96115b769 to your computer and use it in GitHub Desktop.
Thunk Middleware with Custom API Utils
This file contains 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
// 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})); | |
} |
This file contains 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
// 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'}} | |
); | |
}) |
This file contains 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
// 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; |
This file contains 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
// 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