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

7
  • Does this answer your question? How to use an API, that is initialized asynchronously, inside a Vuex state? Commented Sep 9, 2020 at 8:57
  • ... or this? How to load all server side data on initial vue.js / vue-router load? Commented Sep 9, 2020 at 8: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 Commented Sep 9, 2020 at 9:01
  • In your async myCrops method are you calling actionCropId action with await for getting corpId from api response? Commented Sep 9, 2020 at 9: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? Commented Sep 9, 2020 at 9:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.