Skip to content

Instantly share code, notes, and snippets.

@JakeGinnivan
Last active September 4, 2019 09:23
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 JakeGinnivan/a4c74db154591c0a8d590e89a0406635 to your computer and use it in GitHub Desktop.
Save JakeGinnivan/a4c74db154591c0a8d590e89a0406635 to your computer and use it in GitHub Desktop.
function loadArticle(id) {
return async function(dispatch) {
// Dispatch an action indicating we have started loading
// When reduced, the state would likely indicate we
// are in a loading state
dispatch(startLoadArticle(id))
// Perform the load of the data
const loadedArticle = await api.loadArticle(id)
// When done, dispatch finished action, which would
// load the data into the store and exit loading state
dispatch(finishLoadArticle(id, loadedArticle))
}
}
function startLoadArticle(id) {
return {
type: 'START_LOAD_ARTICLE',
payload: { id }
}
}
function finishLoadArticle(id, loadedArticle) {
return {
type: 'FINISH_LOAD_ARTICLE',
payload: { id, loadedArticle}
}
}
function reducer(state = {}, action) {
if (action.type === 'START_LOAD_ARTICLE') {
return {
loading: action.payload.id,
article: undefined
}
}
if (action.type === 'FINISH_LOAD_ARTICLE') {
return {
loading: undefined,
article: action.payload.loadedArticle
}
}
}
store.dispatch(loadArticle(1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment