Created
January 19, 2018 18:39
-
-
Save JaySunSyn/d4c9f8c9253c8eb978b93fa18304d3b5 to your computer and use it in GitHub Desktop.
Step 3
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
<script src="../../node_modules/redux-thunk/dist/redux-thunk.min.js"></script> | |
<script> | |
(() => { | |
const callAPIMiddleware = ({dispatch, getState}) => { | |
return next => action => { | |
const { | |
types, | |
callAPI, | |
shouldCallAPI = () => true, | |
payload = {}, | |
} = action; | |
if (!types) { | |
// Normal action: pass it on | |
return next(action); | |
} | |
if (!Array.isArray(types) || types.length !== 3 || !types.every(type => typeof type === 'string')) { | |
throw new Error('Expected an array of three string types.'); | |
} | |
if (typeof callAPI !== 'function') { | |
throw new Error('Expected callAPI to be a function.'); | |
} | |
if (!shouldCallAPI(getState())) { | |
return; | |
} | |
const [requestType, successType, failureType] = types; | |
dispatch( | |
Object.assign({}, payload, { | |
type: requestType, | |
}) | |
); | |
return callAPI() | |
.then(response => { | |
if (!response.ok) { | |
throw Error(response.statusText); | |
} | |
return response; | |
}) | |
.then( | |
response => { | |
return response.json().then(json => { | |
return dispatch( | |
Object.assign({}, payload, { | |
json, | |
type: successType, | |
}) | |
); | |
}); | |
}, | |
error => | |
dispatch( | |
Object.assign({}, payload, { | |
error, | |
type: failureType, | |
}) | |
) | |
); | |
}; | |
}; | |
App.Middleware = [ | |
ReduxThunk.default, | |
callAPIMiddleware, | |
]; | |
})(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment