Home > Net >  pass data from state to actions vuex
pass data from state to actions vuex

Time:11-06

i want ot pass coords (lat, lng) from state to action to get city name by coordinates, but state.lat & state.lng doesnt work in axios.get url, what i do wrong?

export default new Vuex.Store({
  state: {
    address: [],
    lat: '',
    lng: ''
  },
  mutations: {
    SET_ADDRESS: (state, address) => {
      state.address = address
    },
  },
  actions: {
   async GET_ADDRESS({commit, state}) {
     navigator.geolocation.getCurrentPosition(
         (position) => {
           state.lat = position.coords.latitude
           state.lng = position.coords.longitude
         },
     );
     const address = await axios.get(`https://api.opencagedata.com/geocode/v1/json?q=${state.lat} ${state.lng}&roadinfo=1&key=5032de2d86224227b1d1fbe12f6bf7`,{})
        commit('SET_ADDRESS', address.data.results);
        return address;
    },
  },
  getters: {
    ADDRESS: state => state.address
  }
})

CodePudding user response:

  1. At first: https://vuex.vuejs.org/guide/mutations.html#commit-with-payload

The only way to actually change state in a Vuex store is by committing a mutation.

So the first mistake is mutating state in action:

   state.lat = position.coords.latitude
   state.lng = position.coords.longitude

Second, the first argument passing to navigator.geolocation.getCurrentPosition is a callback. It can be (and it is) called after axios request is executed. So you can send request in that callback.

    export const state = () => ({
      address: []
    });
    
    export const actions = {
      GET_ADDRESS({ commit }) {
        navigator.geolocation.getCurrentPosition(async (position) => {
          const { coords } = position;
    
          const address = await this.$axios.$get(
            `https://api.opencagedata.com/geocode/v1/json`,
            {
              params: {
                q: `${coords.latitude} ${coords.latitude}`,
                roadinfo: 1,
                key: "PUT YOU KEY HERE"
              }
            }
          );
    
          commit("SET_ADDRESS", address.results);
        });
      }
    };
    
    export const mutations = {
      SET_ADDRESS: (state, address) => {
        state.address = address;
      }
    };
    
    export const getters = {
      ADDRESS: (state) => state.address
    };

It's better to use axios params instead string concatenating:

this.$axios.$get(
    `https://api.opencagedata.com/geocode/v1/json`,
    {
        params: {
        q: `${coords.latitude} ${coords.latitude}`,
        roadinfo: 1,
        key: "PUT YOU KEY HERE"
    }
);

Fill it with you API key and check my demo: https://codesandbox.io/s/questions-69858959-pass-data-from-state-to-actions-vuex-o0usb?file=/store/index.js

  • Related