Javascript – How to access Vuex state property from a Vuex action

javascriptvue.jsvuejs2vuex

Currently I have a store with 2 state properties – version and champions + 2 actions that make GET requests and then commit to the state. The second GET requests URL needs to include the version which I've gotten from the first GET request as shown here:

axios.get("https://ddragon.leagueoflegends.com/cdn/" + X + "/data/en_US/champion.json")

The X in this code is supposed to be the Vuex state version property. If I wanted to access that property from outside the Vuex store, I would do it like this:

this.$store.state.version

This doesn't seem to work when I try it in the store though. How am I supposed to access the version state property from inside the getChampions action?

Code:

export default new Vuex.Store({
    state: {
        version: null,
        champions: null
    },
    mutations: {
        version(state, data){
            state.version = data.version
        },
        champions(state, data){
            state.champions = data.champions
        }
    },
    actions: {
        getVersion({commit}){
            axios.get("http://ddragon.leagueoflegends.com/api/versions.json")
            .then((response) => {
                commit('version', {
                    version: response.data[0]
                })
            })
            .catch(function (error) {
                console.log(error);
            })
        },
        getChampions({commit}){
            axios.get("https://ddragon.leagueoflegends.com/cdn/" + X + "/data/en_US/champion.json")
            .then((response) => {
                commit('champions', {
                    champions: response.data.data
                })
            })
            .catch(function (error) {
                console.log(error);
            })
        }
    }
})

Best Answer

you should add another atribute to your function that requires to access state:

getChampions({commit, state}){
            axios.get("https://ddragon.leagueoflegends.com/cdn/" + state.version + "/data/en_US/champion.json")
            .then((response) => {
                commit('champions', {
                    champions: response.data.data
                })
            })
            .catch(function (error) {
                console.log(error);
            })
        }