Search code examples
vue.jsvuejs2nativescriptvuexnativescript-vue

nativescript wait for request until vuex complete request


I have page Login.vue and I am using a strategy if the user already logged in then go to Home Component else stay same

My Code

mounted() {
  this.checkAlreadyLoggedIn();
},
methods: { 
 async checkAlreadyLoggedIn() {
   this.busy = true;
   await this.$store.dispatch("attempt");
   this.busy = false;
   if (this.$store.getters.loggedIn) {
     this.$navigateTo(Home, {
      clearHistory: true
     });
   }
 },
}

attempt action request to server and get users detail but it seems it triggers this.$store.getters.loggedIn early

Thank you


Solution

  • In order to wait properly before checking the getter, and trigger the busy state, return the promise from the attempt action:

    attempt({ state, commit }) {
      return axios.post(...)  // <-- Returning the promise manually
      .then(response => {
        // Commit change
      })
    },
    

    Or with async / await:

    async attempt({ state, commit }) { // <-- async keyword returns promise automatically
      const response = await axios.post(...);
      // Commit change
    }
    

    Here is a demo