When using @pinia/nuxt, an HTTP request is triggered for each iteration of setInterval that occurs outside of the setInterval

I am currently working on creating a timer using @pinia/nuxt within nuxt 3. I also have a requirement to send an http request to sync my database when the timer starts.

However, I'm encountering an issue where the http request is being triggered for each iteration of setInterval when I call the action start, but I only want it to run once.

This particular code snippet pertains to the pinia module. The start action is invoked from an onClick event within a component.

state: () => ({
  timer: {
    id: null,
    isRunning: false,
    time: 5,
    timer: 0,
    state: null,
  } as Timer,
}),
actions: {
  start() {
    this.timer.isRunning = true
    this.syncTimer()
    if (!this.timer.timer) {
      this.timer.timer = setInterval(() => {
        if (this.timer.time > 0) {
          this.timer.time--
        } else {
          clearInterval(this.timer.timer)
          this.reset()
        }
      }, 1000)
    }
  },
  stop() {
    this.timer.isRunning = false
    clearInterval(this.timer.timer)
    this.timer.timer = 0
  },
  reset() {
    this.stop()
    this.timer.time = 1500
  },
  syncTimer() {
    backendAPI<Timer>('/api/timer', {
      method: 'POST',
      body: this.timer
    }).then(({ error, data }) => {
      if (!error.value) {
        const id = data.value?.id ?? ""
        this.timer.id = id
        this.timer.state = "created"
      }
    })
  }
}

Here is the custom fetch composable backendAPI.ts:

import type { UseFetchOptions } from 'nuxt/app'
import { useUserStore } from '@/stores/user'
import { defu } from 'defu'

export function backendAPI<T>(url: string, options: UseFetchOptions<T> = {}) {
  const config = useRuntimeConfig()
  const { token } = useUserStore();
  const appToken = useRuntimeConfig().public.appToken

  const defaults: UseFetchOptions<T> = {
    baseURL: config.public.baseURL ?? 'http://localhost:4000',
    key: url,
    params: {
      token: appToken
    },

    headers: token
      ? { Authorization: `Bearer ${token}` }
      : {},
  }

  const params = defu(options, defaults)

  return useFetch(url, params)
}

Answer №1

It appears that the issue is connected to the nuxt 3 useFetch feature.

As stated in the nuxt documentation:

You can assign computed or ref values to all fetch options. These will be monitored, and any changes will automatically trigger new requests.

Whenever the timer value changes, useFecth will initiate a new request on its own.

The addition of watch: false to the request resolved my issue

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"
  }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing JavaScript code externally on Electron's local server

During local development, I prefer to store all of my separate JS scripts in a different folder. However, the only way I have found to do this is by omitting the declaration of the meta statement. Unfortunately, this omission triggers a warning message. ...

Strategies for constructing or refining an object array with specified key and value from within a typescript object array

Is there a way to extract specific keys and values from an object array by filtering out those with "id" and "level" in TypeScript? Let's break it down with an example: The original object array is structured like this: [{ op: AND id:0 level: ...

Is it advisable to reuse encapsulated constants during unit testing and if so, what is the best

Hey there, I'm currently working on a unit test for a function. While the technical details are not crucial, I thought it would be helpful to provide some code snippets for better understanding. Check out the function below: export function getSalu ...

Challenges arise when trying to display real-time Firebase data in a tabular format

I established a Firebase RealTime database with the following Values: Table: tutorial-vue-eb404 Root: other children year, author, publisher, title Using npm, I initialized my project The configuration was set up by creating firebase.js import Firebase ...

NodeJS makes it easy to transfer files to Azure storage platforms

var BlobSerivceClient = require('@azure/storage-blob'); var multipart = require('parse-multipart'); const AZURE_STORAGE_CONNECTION_STRING = process.env["connectionstringstoragepath"] module.exports = async function (con ...

What is the method to ensure that the data submitted through an HTML form can dynamically update the text content on a webpage?

Trying to set the response of a POST request as the text within an element with id="answer". Here is the HTML form: <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> <script src="http:// ...

Issue occurring while trying to select an item from the dynamically generated options using AJAX

A JavaScript function is used in this code to select a specific option, with the option value being specified within a hidden element: $("select").each(function() { var id = $(this).attr('id'); var source = 'input:hidden[na ...

Generate arrays by extracting each individual value from a multidimensional array based on their corresponding index objects

Witness the example of my primary array: [ { 'data': [{'value': 'Yellow'}, {'value': 'Tiny'}, {'value': 'Excellent'}] }, { 'data': [{'value': 'Gre ...

Issue: The module '@nx/nx-linux-x64-gnu' is not found and cannot be located

I'm encountering issues when trying to run the build of my Angular project with NX in GitHub Actions CI. The process fails and displays errors like: npm ERR! code 1 npm ERR! path /runner/_work/myapp/node_modules/nx npm ERR! command failed npm ERR! c ...

Using Node.js to retrieve a p12 certificate from the certificate repository

Is there a way to retrieve the p12 certificate from the certificate store after it has been installed? I am facing a situation where both the private key and certificate are combined in a p12 certificate and then stored in the Windows certificate store. ...

The _.get function is not compatible with the module.exports object

After exporting an object from a node file, my code is not functioning as expected. (path './../../config/cloud.js): module.exports = { some: { property: 1 } } Even though I am using the following code: const config = require(&ap ...

Transferring Data in Vue.js Components through Props

I've encountered an issue while trying to pass a prop from the main Vue instance to a component. While one of the props is being successfully passed, the second one seems to be causing some trouble. Main Instance var app7 = new Vue({ el: &apos ...

Vue.js Issue: Unable to update Data Store variables using Axios for a GET request?

My current project involves using Vue.js and working with components. Within my Data Store, I have a variable called "comments" that I need to update within the "created" section of the script, so that I can later update my HTML element using a v-for loop ...

Node Webkit - Custom Save As Dialog Supporting Various File Formats

Is it possible to create a 'Save As' feature with multiple file format options using Node Webkit? I am looking for something similar to this desired result: https://i.sstatic.net/ifuxJ.png Currently, with native NW, I can only display two optio ...

Issues with React's useState hook not updating properly

As a React beginner, I am facing an issue with my input field filtering functionality. The problem arises when the results are filtered and rendered, as it seems to be ignoring the last character of the input value. For instance: If I type in "s", nothing ...

Updating Multiple Characters Simultaneously in Text Using JavaScript

I'm faced with the challenge of coloring a table based on its values. For instance, if a cell contains 150%, it should be red; if it's 50%, it should be green. Unfortunately, the text in my table has spaces and '%' symbols scattered thr ...

My stored variable in the php session is not being recalled properly

Currently, my PHP script is generating new files based on user input. I want all documents to be created using the initial input to ensure consistency. In the first PHP script, I set the variable as follows: session_start(); $_SESSION["FirstName"] = $_POS ...

Guide to inserting an Angular routerLink within a cell in ag-Grid

When attempting to display a link on a basic HTML page, the code looks like this: <a [routerLink]="['/leverance/detail', 13]">A new link</a> However, when trying to render it within an ag-Grid, the approach is as follows: src\ ...

Executing asynchronous functions in Angular using ng-click

Within my web application, I am utilizing an ng-table that displays a large number of rows per page (up to 1000). One of the features is a select-all checkbox that triggers an ng-change function to mark each table row as selected. However, the execution ...

What are the steps to effectively implement the useEffect hook in React?

I'm facing an issue where I am trying to return a function that utilizes useEffect from a custom usehook, but I keep getting the error "useEffect is called in a function which is neither a react function component nor a custom hook." Here's what ...