From 803cd81b6618e3051152432fba5d98829ec01c39 Mon Sep 17 00:00:00 2001 From: Matheus Mesquita Date: Sat, 15 Apr 2017 14:08:12 -0300 Subject: [PATCH 1/2] actions chained to prevent unexpected behavior --- src/index.js | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/index.js b/src/index.js index 94c9c00..67b0dbf 100644 --- a/src/index.js +++ b/src/index.js @@ -20,10 +20,14 @@ export default function(store) { failure ] = type - dispatch(requesting()) - - return payload.data() - .then(res => dispatch(success(res))) - .catch(err => dispatch(failure(err))) + const { data:request } = payload; + + return Promise.resolve(requesting) // pass the result of requesting action to promise chain + .then(dispatch) + .then(request) // do the user request call + .then(success) // pass the success action + .then(dispatch) + .catch(failure) // in case of failure of any item in the chain, pass through failure action + .then(dispatch) } } From fe92bf7e04256bf3ddd6353918acac079a881915 Mon Sep 17 00:00:00 2001 From: Matheus Date: Tue, 18 Apr 2017 11:31:19 -0300 Subject: [PATCH 2/2] Fixed: request action not being invoked when starting the chain --- src/index.js | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/index.js b/src/index.js index 67b0dbf..5664616 100644 --- a/src/index.js +++ b/src/index.js @@ -2,9 +2,19 @@ const isArray = type => Array.isArray(type) const isFunc = val => typeof val === 'function' + +/** + * Factory to create action dispatchers + * @param {Function} dispatch - the store dispatcher + * @param {Function} fn - the redux action to be dispatched + * @returns {Function} a function that dispatch data through the redux action + */ +const createDispatcher = (dispatch, fn) => data => { dispatch(fn(data)) } + export default function(store) { - const {dispatch} = store + const { dispatch } = store + return next => action => { @@ -15,19 +25,21 @@ export default function(store) { } const [ - requesting, - success, - failure + requestingAction, + successAction, + failureAction ] = type + const requestingDispatcher = createDispatcher(dispatch, requestingAction); + const failureDispatcher = createDispatcher(dispatch, failureAction); + const successDispatcher = createDispatcher(dispatch, successAction); + const { data:request } = payload; - return Promise.resolve(requesting) // pass the result of requesting action to promise chain - .then(dispatch) + return Promise.resolve() + .then(requestingDispatcher) // pass the result of requesting action to promise chain .then(request) // do the user request call - .then(success) // pass the success action - .then(dispatch) - .catch(failure) // in case of failure of any item in the chain, pass through failure action - .then(dispatch) + .then(successDispatcher) // pass the success action + .catch(failureDispatcher) // in case of failure of any item in the chain, pass through failure action } }