I have a vue project that calls an api to recieve data.
I am using vuex for state management. In my inital call to store.js
where I am controlling the state, the data gets loaded from the api. However if the database I am calling, via the api, gets updated, the new data does not load until the page is refreshed.
I am wondering how the state can update without refreshing the page?
Do I need to use set timer
or something in order to constantly call the api?
Here is my current code for how I am calling the api and saving state:
import Vuex from 'vuex'
import Vue from 'vue'
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
hrM: [],
},
getters: {
},
mutations: {
SET_ML(state, hrM) {
Vue.set(state.hrM = hrM)
},
},
actions: {
loadHrM ({ commit }) {
axios.get("https://my-json-server.typicode.com/.....").then(response => (response.data)).then(hrM => {
commit('SET_ML', hrM);console.log("hrM",hrM)
})
},
}
});
and in the vue code I am calling the state:
mounted() {
this.$store.dispatch('loadHrM')
},
UPDATE:
So far what I have done to update the data is calling a setInterval
:
created(){
const onMessageReceived = () => {
this.$store.dispatch('loadHrM')
}
setInterval(onMessageReceived, 500)
but this is constantly being called and I’m wondering if there is a better method?
Thanks so much!