Home > OS >  Vuex4 state populated with api call is undefined in component
Vuex4 state populated with api call is undefined in component

Time:01-07

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!

CodePudding user response:

In setup function you access state or getter with computed :

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

CodePudding user response:

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),

    }
  }
}

  •  Tags:  
  • Related