Skip to content

Instantly share code, notes, and snippets.

@peerhenry
Last active February 22, 2019 12:41
Show Gist options
  • Select an option

  • Save peerhenry/3de322c81b5b8cf5110de0de9b7c3f17 to your computer and use it in GitHub Desktop.

Select an option

Save peerhenry/3de322c81b5b8cf5110de0de9b7c3f17 to your computer and use it in GitHub Desktop.
infi vuex blogpost refactor 2
const customerModule = {
state: { customer: undefined },
getters: {
customer(state) { return state.customer }
},
mutations: {
setCustomer(state, customer) { state.customer = customer }
},
actions: {}
}
setupApiCall(
customerModule,
'fetchCustomer',
fetchCustomerUrl,
(url, payload) => (fetchCustomerUrl + '?ID=' + payload.customerId), // formatUrl
axios.get, // call
(context, response) => { context.commit('setCustomer', response.data) }, // handleResponse
)
setupApiCall(
customerModule,
'updateCustomer',
updateCustomerUrl,
(url, payload) => (url), // formatUrl
axios.post, // call
(context, response) => (), // handleResponse
)
export customerModule
function setupApiCall(vuexModule, name, url, formatUrl, call, handleResponse) {
const pendingKey = name + 'Pending'
const errorKey = name + 'Error'
const capitalizedName = name.charAt(0).toUpperCase() + name.slice(1)
const pendingMutationKey = 'set' + capitalizedName + 'Pending'
const errorMutationKey = 'set' + capitalizedName + 'Error'
vuexModule.state[pendingKey] = false
vuexModule.state[errorKey] = undefined
vuexModule.getters[pendingKey] = (state) => state[pendingKey]
vuexModule.getters[errorKey] = (state) => state[errorKey]
vuexModule.mutations[pendingMutationKey] = (state, pending) => state[pendingKey] = pending
vuexModule.mutations[errorMutationKey] = (state, error) => state[errorKey] = error
vuexModule.actions[name] = (context, payload) => {
context.commit(pendingMutationKey, true)
context.commit(errorMutationKey, undefined)
const formattedUrl = formatUrl(url, payload)
call(formattedUrl, payload).then(
(response) => {
context.commit(pendingMutationKey, false)
handleResponse(context, response)
},
(error) => {
context.commit(pendingMutationKey, false)
context.commit(errorMutationKey, error)
}
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment