What is the reason for my backend being called twice for every request with the useSWRInfinite function

I have implemented a load more button in a new Next.js application, utilizing the useSWRInfinite hook. Each time the button is clicked, it triggers two calls to the backend. The first call is made with index 0 and the second one with the incremented index.

Below is my component code:

function Home() {
  const { data, size, setSize } = useSWRInfinite(
    (index) => `/api/user?page=${index}&per_page=2`,
    (url) => fetch(url).then((r) => r.json()),
    { initialSize: 1 }
  )
  return <button onClick={() => setSize(size + 1)}>{'load more'}</button>
}

Here is the endpoint used:

export default (req, res) => {
  console.log('calling the backend with', req.query)
  res.send(200)
}

These are the backend logs generated after clicking the button 3 times:

calling the backend with { page: '0', per_page: '2' }
calling the backend with { page: '1', per_page: '2' }
calling the backend with { page: '0', per_page: '2' }
calling the backend with { page: '2', per_page: '2' }
calling the backend with { page: '0', per_page: '2' }
calling the backend with { page: '3', per_page: '2' }

I am curious as to why the backend is called with page/index 0 before calling with the correct incremented index. Any insights on this behavior?

Answer №1

In the useSWRInfinite feature, you have the option to validate the first page before loading each subsequent page. Starting from version 1.1.0, you can disable this by setting

revalidateFirstPage : false

For more information, visit: https://github.com/vercel/swr/releases/tag/1.1.0

  const { data, size, setSize } = useSWRInfinite(
    (index) => `/api/user?page=${index}&per_page=2`,
    (url) => fetch(url).then((r) => r.json()),
    { 
      initialSize: 1, 
      revalidateFirstPage : false 
    }
  )
  return <button onClick={() => setSize(size + 1)}>{'load more'}</button>
}

Answer №2

According to the documentation on swr.vercel.app (link provided), it mentions that the response can be multiple as portrayed in the image below.

https://i.stack.imgur.com/3UAj5.png

If you wish to only make a single request within your getKey function (which may potentially negate the purpose of using useSWRInfinite for implementing pagination), you can modify it as illustrated below:-

https://i.stack.imgur.com/Ws29t.png

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

Can you provide guidance on integrating this jQuery script into my Next.Js application effectively?

I have been using a script on a plain HTML website, importing it via the <script> tag: (function($) { var wa_time_out, wa_time_in; $(document).ready(function() { $(".wa__btn_popup").on("click", function() { if ($(&qu ...

Obtain data with matching JSON values in a REACT application

Recently, I received a JSON file that looks something like this: [ { "symbol": "A", "name": "Agilent Technologies Inc", "exchange": "NYSE", }, { "symbol": "AAC ...

Maximizing efficiency through React/Material UI by leveraging Multiple Div components and inputting dynamic values

I am currently encountering an issue in my React application where I am trying to add multiple divs to a page and send the inputted values to an API. The problem arises when each new div is created, the user's answer gets stored based on states which ...

How can I pass additional props that are not specified in the interface while working with a React TS component?

I am working with a TS React component called MyButton.tsx: import React from 'react' interface MyButtonProps { children: JSX.Element | JSX.Element[], className?: string, variant?: 'big-button' | 'medium-button' | &apos ...

Can anyone guide me on implementing getServerSideProps in a TypeScript NextPage component?

I've come across a page that I'd like to replicate, with the code sourced from https://github.com/dabit3/nextjs-lit-token-gating/blob/main/pages/protected.js: import Cookies from 'cookies' import LitJsSdk from 'lit-js-sdk' ex ...

Navigating state: (TypeError): The mapping function for this.state.[something] is invalid

I am currently working on iterating through my state, which contains data retrieved from an external API. However, I encountered this error message: TypeError: this.state.stocks.map is not a function My goal is to display the results on the frontend dyn ...

Change the state of items in a React component to either disabled or active depending on the active items list retrieved from the API

Obtained from the API, I have a collection of buttons that are displayed for filtering: For instance: button2 button4 button5 Assuming there are a total of 5 buttons. button1 and button3 are supposed to be in a disabled or inactive state (appearing ...

Working with scrollIntoView in useEffect (Encountering an error trying to access 'scrollIntoView' property of null)

Starting from scratch, I'm working on setting up my webpage and crafting some code. function BasicDetails() { React.useEffect(()=>{ scrollView(); }, []); function scrollView() { document.getElementById('main-root& ...

How can I toggle a clicked switch in React MUI instead of all switches?

This is the current state in my parent component: const [feedbackType, setFeedbackType] = useState({ manual: true, auto: false, }); I am passing this state as a prop to the child component. In the child component, I have the following code: co ...

Secrets to concealing a Material UI column based on specific conditions?

Recently, I encountered a challenge with my MUI datagrid where I needed to hide a column based on a specific role. Below is the code snippet: const hideColumn = () => { const globalAdmin = auth.verifyRole(Roles.Admin); if(!globalAdmin){ ...

Eliminate choices in one SELECT menu based on the option selected in another SELECT

const data = [ { "id":1, "name":"Type X", "description":"Description Type X" }, { "id":2, "name":"Type Y", "description": ...

What's the best way to establish the namespace for styled components within a create-react-app environment?

As I work on my react app using create-react-app, I am determined to find a way to customize the generation of classes without needing to eject the webpack config. To achieve this, I have turned to using react-app-rewired along with react-app-rewire-styled ...

Guide to building a react-redux application with a Node server as the backend

Hey there! I'm looking to build a react-redux app with a node server as the backend. Is it feasible for the node server to serve the react-redux app instead of having react-redux run on one port and node on another? Any suggestions on how to kick thi ...

I am struggling to access the props.match.params.id as it seems that the props object is returning as undefined

I've been attempting to extract the id from the URL using props.match.params.id and save it in a variable for future use. However, I'm facing an issue where props is showing as undefined. I'm unsure why this is happening. Could someone kind ...

Exploring Next.js: Leveraging fetch to retrieve data in getServerSideProps and passing it to the client via query parameters

I'm utilizing a getServerSideProps function on the directory page. pages/catalog/index.js export async function getServerSideProps(ctx) { const response = await fetch( `http://someDomen.com/api/ipro/catalog?${ctx?.query?.page ? `page=${ctx.quer ...

The integration of lodash debounce with a NextJS function is failing with the error message "[TypeError: search(...) is undefined]

I've been developing a feature in NextJS that allows users to search for YouTube videos based on their input. In order to optimize API calls, I decided to implement lodash debounce with the useCallback hook. However, I'm encountering an issue whe ...

Guide: Implementing material-ui theme with redux in gatsby

I'm currently utilizing the material-ui theme in conjunction with redux-toolkit within a gatsby project. This is my theme.ts file: import { createMuiTheme } from "@material-ui/core"; import { useSelector } from "react-redux"; import { State } from ". ...

Encountering an issue during deployment of NextJS Release with Azure Web App Deployment task

Struggling to deploy a NextJS or Node project on Azure using DevOps pipeline. I have the steps and configurations set up correctly in the Repo PR, build, and release triggers. However, when the job runs the "Azure Web App Deploy" task, it always encounters ...

Troubleshooting connectivity issues between Entities in microORM and Next.js

While trying to run my Next.js application in typescript, I encountered the following error: Error - ReferenceError: Cannot access 'Member' before initialization After consulting the documentation at https://mikro-orm.io/docs/relationships#relat ...

The CSV/PDF print export feature in Material-UI is not functioning properly when using the "@mui/x-data-grid" module

Is it just me or am I missing something here? I tried to export my data as a PDF using the available export option, but all I see is the CSV option. Why is that? https://i.stack.imgur.com/j6LW6.png In their example, they have access to both CSV and Print ...