Приветствую.
Смотрю в примере корзины от vuex, которую советуют как правильную структуру экшена, они вынесли api в
отдельный файл и потом из экшенов к нему
обращаются.
Думаете такой скелет экшена по работе с API(базой данных) и стоит применять?
По сути что мы тут добились:
- очистили экшены от инфраструктуры (вызовов api), оставив в них только бизнес логику.
- изменения(мутации) в state делаем уже после успешного ответа от api
- есть обработка ошибок
- или есть еще плюсы?
Можете проверить уже по моему реальному коду, все ли я делаю верно по подходу выше?, где у меня есть список городов, вот код ими управляющий:
api/city.js
import axios from 'axios'
export default {
async fetchAllCities(cb, errorCb = null) {
await axios.get('http://localhost:3000/cities')
.then((response) => {
cb(response.data);
})
.catch(function (error) {
if (errorCb) {
errorCb(error);
}
});
},
async addCity(id, name, cb, errorCb = null) {
await axios.post('http://localhost:3000/cities', {
country_id: 1,
id: id,
name: name
})
.then((response) => {
cb(response.data);
})
.catch(function (error) {
if (errorCb) {
errorCb(error);
}
});
},
async deleteCity(id, cb, errorCb = null) {
await axios.delete('http://localhost:3000/cities/' + id )
.then(() => {
cb();
})
.catch(function (error) {
if (errorCb) {
errorCb(error);
}
});
},
async updateCity(id, newName, cb, errorCb = null) {
await axios.put('http://localhost:3000/cities/' + id, {
country_id: 1,
name: newName
})
.then((response) => {
cb(response.data);
})
.catch(function (error) {
if (errorCb) {
errorCb(error);
}
});
},
}
store/index.js
import city from '../api/city'
export default new Vuex.Store({
strict: true,
state: {
cities: []
},
mutations: {
SET_CITIES(state, payload) {
state.cities = payload;
},
ADD_CITY(state, payload) {
state.cities.push(payload);
},
DELETE_LAST_CITY(state) {
state.cities.pop();
},
UPDATE_LAST_CITY(state, payload) {
let ind = state.cities.length - 1;
Vue.set(state.cities, ind, payload);
},
},
getters: {
cities: (state) => {
return state.cities;
},
},
actions: {
async fetchAllCities(context) {
await city.fetchAllCities(
cities => {
context.commit('SET_CITIES', cities);
},
error => console.log('Fetch cities error: ' + error)
);
},
async addCity(context, name) {
let lastId = context.getters.cities[context.getters.cities.length -1].id;
await city.addCity(lastId + 1, name,
(city) => {
context.commit('ADD_CITY', city);
},
error => console.log('Addition error:' + error)
);
},
async deleteLastCity(context) {
let lastId = context.getters.cities[context.getters.cities.length -1].id;
await city.deleteCity(lastId,
() => {
context.commit('DELETE_LAST_CITY');
},
error => console.log('Deletion error: ' + error)
);
},
async updateLastCity(context, newName) {
let lastId = context.getters.cities[context.getters.cities.length -1].id;
await city.updateCity(lastId, newName,
(city) => {
context.commit('UPDATE_LAST_CITY', city);
},
error => console.log('Updation error: ' + error)
);
},
},