[Vuejs]-HTTP request outside setInterval is executed for every setInterval iteration when using @pinia/nuxt

0πŸ‘

βœ…

The problem seems to be related to the nuxt 3 useFetch function.

From the nuxt documentation:

All fetch options can be given a computed or ref value. These will be watched and new requests made automatically with any new values if they are updated.

So every time the timer value is updated, useFecth will automatically make a new request.

Adding watch: false to the request solved my problem

backendAPI<Timer>('/api/timer', {
  method: 'POST',
  watch: false,
  body: this.timer
}).then(({ error, data }) => {
  if (!error.value) {
    const id = data.value?.id ?? ""
    this.timer.id = id
    this.timer.state = "created"
  }
})

0πŸ‘

As I mentioned in the comments, the correct way of implementing realtime feature, is to use sockets. But, if you need to do it in a polling style, you can write a guard, something like this:

actions: {
  start() {
    if (this.timer.isRunning) return;

    this.timer.isRunning = true;
    this.syncTimer();

    this.timer.timer = setInterval(() => {
      if (this.timer.time > 0) {
        this.timer.time--;
      } else {
        clearInterval(this.timer.timer);
        this.reset();
      }
    }, 1000);
  },
  // ...
}

Hope this helps.

Leave a comment