Reputation: 5772
I have a function which takes an ID as an argument and finds the object to which this ID belongs from a JSON that is stored in the Vuex store. So far I have used the function in 1 component only, however, I recently created a second component which also requires that function. Currently I have just copied and pasted the function, however, this seems to be less than optimal. This is why I wonder where should this function be placed so that it's accessible from all components that need it.
I've been wondering if the Vuex store is a viable place to store the function but I'm not too sure so I decided to ask for your advice. Thanks
findChampionName(id){
let championId = id.toString();
let champion = Object.entries(this.$store.state.champions).find(([key,value]) => value.key === championId);
return champion[1]
}
Vuex store:
export default new Vuex.Store({
state: {
champions: null
},
mutations: {
champions(state, data){
state.champions = data.champions
}
},
actions: {
getChampions({commit, state}){
axios.get("https://ddragon.leagueoflegends.com/cdn/9.14.1/data/en_US/champion.json")
.then((response) => {
commit('champions', {
champions: response.data.data
})
})
.catch(function (error) {
console.log(error);
})
}
}
})
Upvotes: 0
Views: 31
Reputation: 27729
As far as I can see, you should use a vuex getter for your case:
getters: {
getChampionName => state => id => {
let championId = id.toString();
let champion = Object.entries(state.champions).find(([key,value]) => value.key === championId);
return champion[1]
}
}
And you can access that getter by passing the id:
this.$store.getters['findChampionName'](id)
Upvotes: 1