Use Vuex getter in component with action's axios data

Viewed 786

When I make a get request, the Vuex action and mutation are updated. However, getters and state are not updated at the same time. It gets updated when I make the second get request.

Vuex Store

import api from '../../api/main'

export const table_informations = {

    state: {
        //  Tek dosya verisi get listesi
        fileName_and_sheetName:[],
        table_value :[]
    },

    getters: {
        Gtable_Value(state){
            return state.table_value
        },
    },

    mutations: {
        Mtable_Value(state,data){
            state.table_value = data
        },
    },

    actions: {
        table_value({commit}){
            api.allshowdata().then(res => res.data).then(items => {
                return commit('Mtable_Value',items)
            })
        },
    },
}

MyTable.vue

<template>
  <div>
    <b-button @click="this.run"></b-button>
  </div>
</template>
<script>
import {table_informations} from "../../../store/file_informations/table_informations";
export default {
  name: "table",
  methods:{
    run(){
      this.$store.dispatch('table_value')
      let data =this.$store.getters.Gtable_Value
      console.log(data)
    }
  },
}
</script>

When I press the button, the action and mutation have up-to-date data, however, state and recipients do not have up-to-date data. When I make the request for the second time, it has up-to-date data. No problem with my action, mutation or get request. Everything is fine except my Vuex store.

1 Answers

You aren't waiting for the async request to complete before setting a variable to the getter value. You should wait for the promise to resolve, but it would be better to use a computed for the getter. This pattern is better if you don't need to do anything else once the getter is loaded.

import { mapGetters } from 'vuex';  // mapGetters
import {table_informations} from "../../../store/file_informations/table_informations";
export default {
  name: "table",
  computed: {
    ...mapGetters(['Gtable_Value']) // Create computed that syncs with Vuex getter
  },
  methods: {
    run() {
      this.$store.dispatch('table_value')
    }
  },
}

Or, to do it the way you planned, return the http promise from the action and wait for it in the method:

store

actions: {
 table_value({commit}){
    // return the http promise
    return api.allshowdata().then(res => res.data).then(items => {
      return commit('Mtable_Value',items)
    })
  },
},

MyTable.vue

import {table_informations} from "../../../store/file_informations/table_informations";
export default {
  name: "table",
  methods: {
    async run() {                                   // async keyword
      await this.$store.dispatch('table_value')     // awaiting the promise
      let data = this.$store.getters.Gtable_Value
      console.log(data)
    }
  },
}
Related