Created
May 2, 2019 14:47
-
-
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.
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
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