Skip to content

Instantly share code, notes, and snippets.

@gledsoncruz
Last active March 2, 2021 19:22
Show Gist options
  • Save gledsoncruz/b70564657218d7b03d0122b3d227e1d0 to your computer and use it in GitHub Desktop.
Save gledsoncruz/b70564657218d7b03d0122b3d227e1d0 to your computer and use it in GitHub Desktop.
/* eslint-disable no-empty-pattern */
/* eslint no-shadow: ["error", { "allow": ["state"] }] */
import { baseApiUrl, showError } from '@/global';
import axios from 'axios';
const state = {
bairros: [],
};
const actions = {
async loadAll({ commit }) {
const url = `${baseApiUrl}/endereco/bairros.json`;
await axios.get(url).then((res) => {
commit('SET_BAIRROS', res.data.results);
}).catch(showError);
},
async saveOrUpdate({ commit }, bairro) {
const method = bairro.id ? 'patch' : 'post';
const id = bairro.id ? `${bairro.id}/` : '';
await axios[method](`${baseApiUrl}/endereco/bairros/${id}`, bairro)
.then((res) => {
if (!id) {
commit('ADD_BAIRRO', res.data);
} else {
commit('EDIT_BAIRRO', res.data);
}
}).catch(showError);
},
async remove({ commit }, bairro) {
const id = bairro.id;
await axios.delete(`${baseApiUrl}/endereco/bairros/${id}`)
.then(() => {
commit('DELETE_BAIRRO', id);
}).catch(showError);
},
};
const getters = { };
const mutations = {
SET_BAIRROS: (state, bairros) => {
state.bairros = bairros.map(bairro => ({
...bairro, value: bairro.id, text: bairro.nome,
}));
},
ADD_BAIRRO: (state, bairro) => {
state.bairros.push(bairro);
},
EDIT_BAIRRO: (state, bairro) => {
const index = state.bairros.findIndex(i => i.id === bairro.id);
state.bairros.splice(index, 1);
state.bairros.push(bairro);
},
DELETE_BAIRRO: (state, id) => {
const index = state.bairros.findIndex(i => i.id === id);
state.bairros.splice(index, 1);
},
};
export default {
namespaced: true,
state,
mutations,
actions,
getters,
}
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment