Reputation: 1202
I have a Vuex
instance which loads data from API
. The first time I access the store it should load the data from API, and when I access it again it should return the loaded data from the store.empresas
. This is how my Vuex module looks like:
import Empresas from '@/api/empresas'
import moment from 'moment'
export default {
state: {
loaded: false,
lastLoadedDate: null,
empresas: []
},
getters: {
empresas: state => {
if (!state.loaded || moment().diff(state.lastLoadedDate, 'minutes') > 30) {
//Was not loaded yet or was loaded more than 30 minutes ago,
//Sould load from api -> actions.carregarEmpresas()
//Don't know how to proceed here
} else {
//Already loaded
return state.empresas
}
}
},
mutations: {
setEmpresas (state, payload) {
state.loaded = true
state.lastLoadedDate = moment()
state.empresas = payload
}
},
actions: {
carregarEmpresas ({ commit }) {
Empresas.listar()
.then(({ data }) => {
commit('setEmpresas', data.empresas)
})
}
}
}
The reason I need this is that I will need to access empresas
in multiple files in my application, and I don't want to make an API call every time.
However, I don't know how to implement it inside the getter. Is it possible to do it?
Upvotes: 3
Views: 1211
Reputation: 281
This might be a duplicate of this post: Can I do dispatch from getters in Vuex. Check if the second answer helps you.
Basically, you shouldn't call actions from you getters. I would recommend you call the action at the initial load of the app. Then you will just use the getter without the conditional.
Upvotes: 2