Mads
Mads

Reputation: 127

Vue - Best way to poll the same API endpoint for multiple components simultaneously

I need to fetch continuously updating API endpoint data for several components on my NUXT site, 2 of which are visible simultaneously at any given moment. I wonder what is the best practice to poll the same endpoint for several different components visible at the same time?

Currently, I am using VUEX to send the API data to my components and then using setInterval with a refresh function to update the data in each component. This is clearly a clumsy solution (I am a beginner). I was thinking about polling the API directly in VUEX but I understand this is not advisable either.

This is my current (clumsy) solution:

VUEX:

// STATE - Initial values
export const state = () => ({
  content: {}
});


// ACTIONS 
export const actions = {
    async nuxtServerInit ({ commit }) {
        const response = await this.$axios.$get('https://public.radio.net/stations/see15310/status');
        commit('setContent', response)
    }
}

// MUTATIONS 
export const mutations = {
    setContent(state, content) {
      state.content = content;
    }
  }

  

And in each component:

    computed: {
    content () {
      return this.$store.state.content
    },

    methods: {
      refresh() {
        this.$nuxt.refresh()
      }
    },

    mounted() {
      window.setInterval(() => {
        this.refresh();
      }, 5000);

Upvotes: 0

Views: 3444

Answers (1)

Anatoly Zolotov
Anatoly Zolotov

Reputation: 46

I think, it's a normal solution to do the polling in vuex. Vuex is your application state and the one source of truth for all dependant components. And if you need to update some similar state for different components - it's a rational solution to do it in vuex action.

Another solution could be the event bus. First article about it from google

Also, I don't recommend use SetInterval for polling. Because it's don't wait of async operation ending. This fact could shoot you in the foot, if a client has network delay or another glitch. I used SetTimeout for this purpose.

async function getActualData() {
  // get data from REST API
}

async function doPolling() {
  const newData = await getActualData() // waiting of finish of async function
  // update vuex state or send update event to event bus

  setTimeout(doPolling, 5000)
}

doPolling()

If my answer missed into your question, then give me more details please. What is the problem you want to solve? And what disadvantages do you see in your(by your words ;) ) "clumsy" solution?

Upvotes: 1

Related Questions