Created
April 21, 2016 15:45
-
-
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?
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
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