Last active
April 19, 2017 15:14
-
-
Save davidharting/47f60477ad600ba536a548e369905a47 to your computer and use it in GitHub Desktop.
This provides an example of a factory for asynchronous actions that handle making HTTP requests and dealing with the response and errors.
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
/** | |
* Assumptions: | |
* - Using redux-thunk middleware | |
* - requester is an HTTP client service | |
* - normalizr function provided by a library (e.g., normalizr, json-api-normalizr) | |
*/ | |
function createApiGetAsyncAction(resource, namespace) { | |
return function asyncAction() { | |
return function thunk(dispatch) { | |
dispatch({ type: `${namespace}/get/REQUEST` }) | |
return requester.get(resource) | |
.then(function handleResponse(response) { | |
if (!response.isOk) { | |
throw new Error(`Received an error response from the server after requesting GET for resource "${resource}": ${JSON.stringify(response)}`) | |
} | |
const data = normalize(response) | |
dispatch({ | |
type: `${namespace}/get/SUCCESS`, | |
data | |
}) | |
}) | |
.catch(function handleError(error) { | |
console.error(`Encountered an error while attempting to GET ALL for type "${resource}". ${error.message}`) | |
dispatch({ | |
type: `${namespace}/get/FAILURE`, | |
error | |
}) | |
}) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment