I have a Vuex
instance that is responsible for fetching data from an API
. The initial access to the store should trigger a call to load the data from the API. Subsequent accesses should return the previously loaded data stored in store.empresas
. This is the structure of my Vuex module:
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) {
// Data was not yet loaded or it was loaded more than 30 minutes ago,
// Should fetch from the API -> actions.carregarEmpresas()
// Unsure how to proceed here
} else {
// Data 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 main reason for this setup is because I will be accessing the empresas
data in various parts of my application and I want to avoid making repeated API calls.
However, implementing this logic inside the getter has posed a challenge. Is there a way to achieve this?