Skip to content

Instantly share code, notes, and snippets.

@webmasterdevlin
Created March 13, 2019 02:29
Show Gist options
  • Save webmasterdevlin/99d5e533e7a4e9c77bed7bb23ccf77bf to your computer and use it in GitHub Desktop.
Save webmasterdevlin/99d5e533e7a4e9c77bed7bb23ccf77bf to your computer and use it in GitHub Desktop.
Vuex Actions: src/store/modules/heroes/actions.js
import * as types from "../../types";
import heroesService from "../../../services/heroes-services";
const actions = {
[types.ACTION_GET_HEROES]({ commit }) {
return new Promise(resolve => {
heroesService
.getHeroes() // getHeroes() is a method in my HeroesServices that sends get request to a backend service.
.then(data => {
commit(types.MUTATE_GET_HEROES, data); // commit does the changes in your state.
resolve();
})
.catch(err => {
alert("Something happened: " + err);
});
});
},
[types.ACTION_GET_HERO]({ commit }, id) {
return new Promise(resolve => {
heroesService
.getHero(id)
.then(data => {
commit(types.MUTATE_GET_HERO, data);
resolve();
})
.catch(err => {
alert("Something happened: " + err);
});
});
},
[types.ACTION_ADD_HERO]({ commit }, heroData) {
return new Promise(resolve => {
heroesService
.addHero(heroData)
.then(data => {
commit(types.MUTATE_ADD_HERO, data);
resolve();
})
.catch(err => {
alert("Something happened: " + err);
});
});
},
[types.ACTION_UPDATE_HERO]({ commit }, hero) {
return new Promise(resolve => {
heroesService
.updateHero(hero)
.then(data => {
commit(types.MUTATE_UPDATE_HERO, data);
resolve();
})
.catch(err => {
alert("Something happened: " + err);
});
});
},
[types.ACTION_REMOVE_HERO]({ commit }, hero) {
return new Promise(resolve => {
heroesService
.removeHero(hero)
.then(() => {
commit(types.MUTATE_REMOVE_HERO, hero.id);
resolve();
})
.catch(err => {
alert("Something happened: " + err);
});
});
}
};
export default actions;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment