Last active
July 20, 2016 17:39
-
-
Save Arturszott/f591a62166479a43879e278b1d2f1c52 to your computer and use it in GitHub Desktop.
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
// 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