Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mbilokonsky/569ed6a1f44575ba9193181da3a3ab8e to your computer and use it in GitHub Desktop.
Save mbilokonsky/569ed6a1f44575ba9193181da3a3ab8e to your computer and use it in GitHub Desktop.
An attempt to generify redux ajax thunk generation. this generates the action types and the action creator for you, but you'd still have to write your reducer. Worthwhile?
function createAsyncFeature(name, url) {
const actionTypes = {
name + "_INVALIDATED": name + "_INVALIDATED",
name + "_RETRIEVED": name + "_RETRIEVED",
name + "_FAILED": name + "_FAILED"
}
const createInvalidatingAction() {
return {
type: actionTypes[name + "_INVALIDATED"],
meta: {
timestamp: Date.now()
}
}
}
const createRetrievalAction(json) {
return {
type: actionTypes[name + "_RETRIEVED"],
payload: json,
meta: {
timestamp: Date.now()
}
}
}
const createErrorAction(err) {
return {
type: actionTypes[name + "_FAILED"],
payload: err,
error: true,
meta: {
timestamp: Date.now()
}
}
}
const actionCreator = function() {
return function(dispatch) {
dispatch(createInvalidatingAction());
return fetch(url, {headers: {'Content-Type': 'application/JSON'}})
.then(response => response.json())
.then(json => dispatch(createRetrievalAction(json)))
.catch(err => dispatch(createErrorAction(err)))
}
}
return {
name,
actionTypes,
actionCreator
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment