Skip to content

Instantly share code, notes, and snippets.

@Arturszott
Last active July 20, 2016 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Arturszott/f591a62166479a43879e278b1d2f1c52 to your computer and use it in GitHub Desktop.
Save Arturszott/f591a62166479a43879e278b1d2f1c52 to your computer and use it in GitHub Desktop.
// thunk based action creator example, cannot be tested while calling mapDispatchToProps beside checking if dispatch was called
function saveScore (score) {
return (dispatch) => {
fetch('/scores', { method: 'POST', { score } })
.then(() => {
dispatch({ type: SAVE_SCORE_SUCCEEDED })
})
}
}
// used to created dispatchable object that is easy to test
function createThunkObject (type, payload, actionCreator) {
return {
type: `@@THUNK_OBJECT@@_${type}`,
payload,
actionCreator
};
}
// middleware that inject payload to action creator
const preThunkMiddleware = store => next => action => {
if (action.type && action.type.indexOf('@@THUNK_OBJECT@@') === 0) {
next(action);
} else {
next(action.actionCreator(action.payload));
}
}
// usage example in mapDispatchToProps
function mapDispatchToProps(dispatch) {
return {
saveScore: (score) => { dispatch(createThunkObject('SAVE_SCORE', score, saveScore)) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment