0

When I am loading a getter that returns an id in computed property. I try to print the 'id' in a method, the id value is empty for the first time when app loads. But then, when i edit a file and save I can see this id is getting printed in console. Or when I do setTimeout of 1 sec, I can see the getter.

This 'id' value is important and I want to access as a global variable. I want it access crop id right when app load. Because based on this value I will be making a few api calls.

The crop id is set from result of a api call.

store.commit("setCropId", list.id);

My vuex

state:{
    crop: ""
},
mutations: {
    setCropId(state, value) {
      state.crop = value;
    }
},
actions:{
    actionCropId ({ commit }, value) {
     commit('setCropId', value)
    }
},
getters: {
    getCropId: state => {
      return state.crop;
    }
}

My vue component

import { mapGetters } from "vuex";
  computed: {
    ...mapGetters([
      'getCropId',
    ])
  },
  mounted() {
    this.myCrops();
  },
  methods: {
    async myCrops() {
     console.log('my crops', getCropId)
     // other logic
    }
  }

I dont know how to make it work. Please suggest if I am doing anything wrong or how to get getters right away when app loads.

Thank you

user8532998
  • 21
  • 1
  • 3
  • Does this answer your question? [How to use an API, that is initialized asynchronously, inside a Vuex state?](https://stackoverflow.com/questions/60767946/how-to-use-an-api-that-is-initialized-asynchronously-inside-a-vuex-state) – Phil Sep 09 '20 at 08:57
  • ... or this? [How to load all server side data on initial vue.js / vue-router load?](https://stackoverflow.com/questions/41572974/how-to-load-all-server-side-data-on-initial-vue-js-vue-router-load) – Phil Sep 09 '20 at 08:58
  • the api call is made in router.beforeEach((to, from, next) => { // my api call then store.commit("setCropId", list.id); }); This is fine but its the getters not showing up when call in method in my component right after loading app – user8532998 Sep 09 '20 at 09:01
  • In your async myCrops method are you calling actionCropId action with await for getting corpId from api response? – Kalleshwar Kalshetty Sep 09 '20 at 09:46
  • @KalleshwarKalshetty no, u mean store.dispatch('actionCropId') ? I thought this was not necessary because my getter is set in router before the component loads. So it would be just fetching the getter and not calling the action. Am I wrong? – user8532998 Sep 09 '20 at 09:51
  • From whatever code you have here i think its because you are consoling getCropId before its getting commited in store. check your async await action call. – Kalleshwar Kalshetty Sep 09 '20 at 10:00
  • @KalleshwarKalshetty ok I will, thank you, I suspect the lifecycle is like that – user8532998 Sep 09 '20 at 11:39

0 Answers0