Skip to content

Instantly share code, notes, and snippets.

@davidharting
Last active April 19, 2017 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidharting/47f60477ad600ba536a548e369905a47 to your computer and use it in GitHub Desktop.
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.
/**
* 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