Vuex accessing state BEFORE async action is complete Vuex accessing state BEFORE async action is complete vue.js vue.js

Vuex accessing state BEFORE async action is complete


store.dispatch can handle Promise returned by the triggered action handler and it also returns Promise. See Composing Actions.

You can setup your selected action to return a promise like this:

selected: ({commit}, payload) => {    return new Promise((resolve, reject) => {        commit('selected', payload);    });} 

Then in your SearchResults.vue instead of using a router-link use a button and perform programmatic navigation in the success callback of your selected action's promise like this:

<template><div>  //looped  <button @click.native="selected(Object)">       <p>{{Object}}</p>  </button></div></template><script>export default {  methods: {    selected(show){      this.$store.dispatch('selected', show)          .then(() => {            this.$router.push('ShowDetails');        });    },  },}</script> 


You can try to use v-if to avoid rendering template if it is no search results

v-if="$store.getters.searchResult"


Initialize your states.As with all other Vue' data it is always better to initialize it at the start point, even with empty '' or [] but VueJS (not sure if Angular or React act the same, but I suppose similar) will behave much better having ALL OF YOUR VARIABLES initialized.

You can define initial empty value of your states in your store instance.

You will find that helpful not only here, but e.g. with forms validation as most of plugins will work ok with initialized data, but will not work properly with non-initialized data.

Hope it helps.