When building applications you often need to communicate with other services or your back-end API. A lot of the times in your Vue application you find yourself having actions like below.
export const getUsers = ({commit}, params) => { | |
return axios.get('http://api.domain.com/users', { | |
params | |
}).then(resp => { | |
commit('GET_USERS_SUCCESS', resp.data) | |
return resp.data | |
}) | |
} | |
export const getDrivers = ({commit}, params) => { | |
return axios.get('http://api.domain.com/drivers', { | |
params | |
}).then(resp => { | |
commit('GET_DRIVERS_SUCCESS', resp.data) | |
return resp.data | |
}) | |
} |
While there is absolutely nothing wrong with the actions, you realize that there is repetition in the two actions. Lets identify the repetitions and simplify the code.
There are 3 ways you can simplify the above code.
- Set a base API URL. I am using axios to make my requests.
axios.defaults.baseURL = 'http://api.domain.com' | |
//then later in your actions | |
axios.get('/users') // to minimize typing the domain in full | |
// getDrivers | |
axios.get('/drivers') |
- Since they are both get request, you can merge them into one and make the get request more generic.
export const get = ({commit}, {url = '', params = {}}) => { | |
axios.get(url, { | |
params | |
}).then(resp => { | |
return resp.data | |
}) | |
} |
- You have to be keen on commit since not all get requests get persisted to the vuex store. It all depends on your application though.
export const get = ({commit}, {url = '', params = {}, type = '', canCommit = true}) => { | |
axios.get(url, { | |
params | |
}).then(resp => { | |
if (canCommit) { | |
commit(type, resp.data) | |
} | |
return resp.data | |
}) | |
} |
Now when you need to issue another get request i.e. getAllShops getUserLogs you will not need to setup separate actions for getting shops and user logs . All you need to do in your component is
//get all shops | |
const shops = await this.$store.dispatch('get', { | |
url: '/shops', | |
params: { | |
type: 'all' | |
}, | |
type: 'GET_SHOPS_SUCCESS' | |
}) | |
// use your response if you need to | |
//get user logs | |
const logs = await this.$store.dispatch('get', { | |
url: `/users/${userId}/logs`, | |
canCommit: false | |
}) |
You can do the same for POST, PUT AND DELETE requests. This is how I handle requests in my applications and I can tell you for a fact it has increased my development speed.
Top comments (5)
emmmh ... I think that something is missing ...
I appreciate your suggestion. Whats missing?
you wrote: "A lot of the times in your Vue application you find yourself having actions like below"
... but I don't find any code "below" !
maybe a strange behaviour of my browser ?
Thanks for pointing that out. Hope it is now sorted.
it's all right now (baby blue) !!