Looping through GET requests

I have a Next.js and TypeScript application where a request is made to a webhook integration that returns a Google sheet in JSON format. I've noticed that the integration keeps getting called repeatedly in a loop.

Here is a snippet of my code:

import { useQuery, UseQueryResult } from "@tanstack/react-query";

const useFetchData = <T>(url: string, queryKey: string): UseQueryResult<T> => {
  return useQuery<T>({
    queryKey: [queryKey],
    queryFn: async () => {
      console.log(`Fetching data from: ${url}`);
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`Network response was not ok: ${response.statusText}`);
      }
      const data = await response.json();
      console.log("Data fetched:", data);
      return data;
    },
  });
};

export default useFetchData;

Even though I've added logs and confirmed that the page is not being re-rendered, the request to the integration keeps happening repeatedly. I'm struggling to identify the cause of this issue.

Answer №1

To manage how often requests are made, leverage the staleTime and cacheTime parameters within the useQuery function. By setting staleTime, you can control how long the data remains fresh, while cacheTime determines how long inactive data is kept in the cache. Increasing staleTime can reduce unnecessary data refetching. However, remember that the primary function of useQuery is to fetch data continuously when needed. If your goal is to retrieve data only upon a button click or initial render, there may be no need to use useQuery.

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

The phenomenon of an invisible Absolute or relative position leading to grid components overlapping in Next.js

I've been struggling with this issue for over 48 hours now. I've attempted to troubleshoot by commenting out everything except the affected components and even swapping entire components around, but the problem persists. Oddly enough, rearranging ...

The Axios function is unable to read the 'Ok' value because of undefined properties

I suspect there is something missing in my argument, but I am attempting to call HttpStatusCode.Ok from the Axios Enum. Here is how I have implemented it: import { HttpStatusCode } from 'axios' console.log(HttpStatusCode.Ok) However, I encounte ...

What is the method for displaying data from a JSON file that is associated with the wallet address of the authenticated user in next.js?

I am currently working on a claim page using next.js, where logged in Metamask addresses can perform the following tasks: Access data from a local .json file to check eligibility for claiming an item and display the claim page. Submitting a form to update ...

The ultimate guide to generating pristine Image URLs in Next.js with the next/image component

I'm interested in learning how to generate clean image URLs using the next/image component in Next.js. Here is an example of a current URL: https://www.example.com/_next/image?url=%2Fimages%2Fhome%2/Dog-image-1.jpg&w=384&q=100 Is it possibl ...

The scrolling experience in Next js is not as smooth as expected due to laggy MOMENTUM

Currently, I am in the process of constructing my portfolio website using Next.js with Typescript. Although I am relatively new to both Next.js and Typescript, I decided to leverage them as a learning opportunity. Interestingly, I encountered an issue with ...

React Router Issue: Component Not Rendering When <nav> Element Is Incomplete

I am currently experiencing an issue with rendering a component in my React TypeScript application using React Router. The problem arises when trying to navigate to the AddTask component by clicking on a link within a <nav> element. Strangely, the co ...

How to seamlessly incorporate Polymer Web Components into a Typescript-based React application?

Struggling to implement a Polymer Web Components tooltip feature into a React App coded in TypeScript. Encountering an error during compilation: Error: Property 'paper-tooltip' does not exist on type 'JSX.IntrinsicElements' To resolve ...

Abrupt surge in Firestore read operations detected in Next.js application following a period of no modifications - refer to the accompanying visual

https://i.sstatic.net/vim7m.png During the initial 10 days of working on the project, I noticed a consistent range of reads between 100 - 300 per day while regularly refreshing documents from firestore. Days 11-15 were spent away from the project visiting ...

Images are failing to render on Next.js

Hello there! I am facing an issue while working on my Next.js + TypeScript application. I need to ensure that all the images in the array passed through props are displayed. My initial approach was to pass the path and retrieve the image directly from the ...

Combining useEffect with getServerSideProps in Next.js for optimal data fetching

While working on my project with next.js, I encountered a problem where the getServerSideProps function is being called 6 times when the page is loaded. Here is the code snippet from the pages section: const NewFindstay: React.FC<INewFindstayProps> ...

Nginx fails to correctly proxy Next.js app

My server has nginx installed directly, with a proxy to a Docker container that holds a Next.js application. The HTML of the Next.js is loading correctly, but all the assets are failing: server { listen 443 ssl http2; listen [::]:443 http2; s ...

What causes the Angular child component (navbar) to no longer refresh the view after a route change?

Hello everyone, I'm excited to ask my first question here. Currently, I am working on developing a social network using the MEAN stack and socket.io. One of the challenges I am facing is displaying the number of unread notifications and messages next ...

When implementing `redux-observable` with NextJS, the `HYDRATION` action may not properly receive the server payload

Packages: redux-observable@2.0.0-rc.2 rxjs latest universal-rxjs-ajax dev branch next-redux-wrapper latest next.js latest I am working on a simple Page with getStaticProps: export const getStaticProps = wrapper.getStaticProps((store) => async (ctx) =& ...

Refactor TypeScript in Visual Studio Code: Relocate class from one file to another (already existing) file

One common task when reorganizing a project with numerous classes is to transfer certain classes to an already existing file. After exploring various vscode features and extensions, I have not come across any refactoring tool that allows for this specific ...

The query parameter is not defined in the router of my Next.js app API

I'm currently working on building an API endpoint for making DELETE requests to remove albums from a user's document in the MongoDB Atlas database. Struggling with an error that keeps popping up, indicating that the albumName property is undefin ...

ReactJs: How useEffect is invoked before onClick function in NextJS

I am facing an issue with a button in my Next project. Here is the code for the button: <Button minWidth={'140px'} onClick={() => exec(scope)} >Save</Button> When this button is clicked, it triggers the following function: c ...

The dark mode class in Next.js/React does not take effect until a local change is made

I've been diving into a helpful tutorial on implementing dark mode toggle in my project. The tutorial uses react-toggle and can be found here. Everything seems to be working fine except for one issue that arises on the initial page load. When the bro ...

Tips on adding an image using Reactjs

I am currently working in Reactjs with the Next.js framework. I am attempting to upload images using Axios (POST method API) and will be utilizing an "api in PHP". Could someone please guide me on how to achieve this? I have tried the code below, but it&ap ...

Data from graphql is not being received in Next.js

I decided to replicate reddit using Next.js and incorporating stepzen for graphql integration. I have successfully directed it to a specific page based on the slug, but unfortunately, I am facing an issue with retrieving the post information. import { use ...

Discovering the proper way to infer type for tss-react withParams and create

Greetings to everyone and a huge thank you in advance for your generous help. I have a desire to utilize the tss-react library for styling, particularly because I will be implementing Material UI components. As I delve into some documentation, the latest A ...