My current solution works: I get the data from the API. But Vue doesn't like it.
What is the proper way to use setInterval within the Vuex store without "mutating the vuex store state outside mutation handlers"?
In Index.vue:
mounted () {
store.dispatch('setAPIEndpoint', {
endpoint: 'chillersystem',
requestType: 'post',
payload: {},
})
},
In actions.js:
async setAPIEndpoint ({ commit }, payload) {
commit('SET_API_ENDPOINT', payload)
}
In mutations.js:
SET_API_ENDPOINT (state, payload) {
// Clear the previous interval to prevent a memory leak
if (state.api.interval !== null) {
state.api.interval = null
state.api.data = {}
}
// Reset the API parameters
state.api.endpoint = payload.endpoint
state.api.requestType = payload.requestType
state.api.payload = payload.payload
// Schedule repetition
state.api.interval = setInterval(() => {
if (state.api.requestType === 'post') {
axios.post(`/api/${ state.api.endpoint }`, state.api.payload)
.then((response) => {
state.api.data = response.data
})
.catch((error) => {
process.env.NODE_ENV === 'production' ? location.href = 'pages/error-500/' : console.log(error)
})
}
}, state.api.refreshTimer)
}
In state.js
const state = {
api: {
endpoint: '',
requestType: '',
payload: {},
data: {},
refreshTimer: 5000, // Milli-seconds
interval: null
}
}
