简体   繁体   中英

Vuex4 state populated with api call is undefined in component

Please bare with me I am still new to using Vuex and don't quite understand it yet. I am using Vuex4 with localforage package for IndexedDB.

My Vuex store is as follows:

import { createStore } from 'vuex'
import localforage from 'localforage'
import axios from 'axios'

const store = createStore({
  state: {
    tenantLocale: {}
  },
  getters: {},
  mutations: {
    setLocale(state, value) {
      state.tenantLocale = value
    }
  },
  actions: {
    getTenant(context) {
      axios.get('/api/tenant-data/locale').then((response) => {
        context.commit('setLocale', response.data)
        localforage.setItem('tenantLocale', response.data)
      })
    }
  }
})

export default store

I dispatch the action in my App.vue like this:

import { useStore } from 'vuex'

export default {
  setup() {
    const store = useStore()

    //get default information about tenant from api
    store.dispatch('getTenant')

    return {}
  }
}

The thing is now if I render the state in my Login.vue component in the template section like so:

<h1>{{ store.state.tenantLocale.timezone }}</h1>

It shows the correct data, but if I try to do something with it in the script section of my component lets say for example try to print it out:

console.log(store.state.tenantLocale.timezone)

I get the undefined message.

What am I missing here? What would be the best approach here? Do I need to create getter for it? Create a promise? My brain is fried... Any help to at least point me in the right direction is appreciated!

In setup function you access state or getter with computed:

computed(() => store.state.tenantLocale.timezone)

You can do like this

 import { computed } from 'vue' import { useStore } from 'vuex' export default { setup () { const store = useStore() return { // access a state in computed function timezone: computed(() => store.state.tenantLocale.timezone), } } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM