Skip to content

Instantly share code, notes, and snippets.

@horaciosystem
Created May 2, 2019 14:47
Show Gist options
  • Save horaciosystem/0680b99dbb5a7a489db8784b7329dc85 to your computer and use it in GitHub Desktop.
Save horaciosystem/0680b99dbb5a7a489db8784b7329dc85 to your computer and use it in GitHub Desktop.
A Vuex helper to generate async actions with same shape and less boilerplate.
export default function createAsyncAction({
key,
methodName,
handler,
initialState = null,
stateUpdater = ({ currentData }) => currentData
}) {
let [setLoading, setError, setData] = [
`${key}SetLoading`,
`${key}SetError`,
`${key}SetData`
]
return {
state: {
[key]: {
loading: false,
error: null,
data: initialState
}
},
mutations: {
[setData]: function(state, data) {
state[key].data = data
},
[setLoading]: function(state, loading) {
state[key].loading = loading
},
[setError]: function(state, error) {
state[key].error = error
}
},
actions: {
[methodName]: function({ commit, state }, params) {
commit(setLoading, true)
return handler(params)
.then(data => {
let newData = stateUpdater({
prevState: state[key].data,
currentData: data
})
commit(setData, newData)
})
.catch(error => commit(setError, error))
.finally(() => commit(setLoading, false))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment