Vue, how to update state in vuex

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'


export default new Vuex.Store({
  state: {
    hrM: [],
  getters: {
  mutations: {
    SET_ML(state, hrM) {
      Vue.set(state.hrM = hrM)
  actions: {
    loadHrM ({ commit }) {
     axios.get("").then(response => ( => {
          commit('SET_ML', hrM);console.log("hrM",hrM)

and in the vue code I am calling the state:

mounted() {

So far what I have done to update the data is calling a setInterval:

	const onMessageReceived = () => {
   setInterval(onMessageReceived, 500)

but this is constantly being called and I’m wondering if there is a better method?
Thanks so much!

If you want the server to notify you when there have been updates you really only have a few options.

    1. Polling the server as you are doing now. You’ll just want to make sure you cleanup that polling code whenever the component unmounts.
    1. Having the server send you updates using WebSockets
    1. Having the server push notifications using SSE(Server Sent Events)
1 Like

Thanks so much for your help and ideas. I’m gonna try to look into WebSockets and SSE as well.

Also I’ve been doing some research on WebSockets and I’m wondering if they can connect to non socket servers?

For example, I made a mock server with that I would like to get the data from. When I tried connecting to it via WebSockets I got errors. When I looked into it online, I saw some comments about not being able to use with non socket servers.

Both the browser and the server need to communicate over a WebSocket. So you can’t initiate a WebSocket connection with any server endpoint. The server must be setup properly for it to work.

1 Like

Now I understand, thanks so much!!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.