Skip to content

When using two useSWRInfinite in one page, initialPageSize of one is overwritten by initialPageSize of other. #4082

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
PSoltes opened this issue Jan 30, 2025 · 2 comments

Comments

@PSoltes
Copy link

PSoltes commented Jan 30, 2025

Bug report

Description / Observed Behavior

Environment

  • Next 14 - app router
  • Node 22
  • Linux Mint
    Behaviour
  • two useSWRInfinite hooks are used in one page (page.tsx)
  • first has initial page size set to n
  • second has initial page size set to m
  • on page load
    • first returns correct size of n
    • second first returns correct size of m, then it is overwritten to n

Expected Behavior

Each instance of hook respects its initial configuration

Repro Steps / Code Example

"use client";

import useSWRInfinite from "swr/infinite";

const fetcher = async (key: string) => {
  const resp = await fetch(key);
  if (!resp.ok) {
    throw new Error("error");
  }
  return resp.json();
};

export default function SWR() {
  const {
    size: sizeForward,
    setSize: setSizeForward,
    ...swrRestForward
  } = useSWRInfinite((size) => `/api/infinite-fake-api?page=${size}`, {
    initialSize: 2,
    fetcher,
  });

  const {
    size: sizeBackward,
    setSize: setSizeBackward,
    ...swrRestBackward
  } = useSWRInfinite((size) => `/api/infinite-fake-api?page=${size}`, {
    initialSize: 12,
    fetcher,
  });

  console.log(
    swrRestBackward.data,
    sizeBackward,
    swrRestForward.data,
    sizeForward
  );
  return <main></main>;
}

Additional Context

"swr": "2.3.0"

To as to why two useSWRInfinite hooks with "same" key - to react-query behaviour of fetching previous page. eg. first page I'll fetch will be fifth one and then I want to either go back of forward.

Image

@PSoltes
Copy link
Author

PSoltes commented Jan 30, 2025

Oh it is because of the "same" key. I guess I can workaround by adding something extra and handling in custom fetcher.

@ddoice
Copy link

ddoice commented Feb 19, 2025

Did you manage to get it working @PSoltes ? I'm facing the same issue but the key workaround is a bit overkill for my use case because i'll trigger a lot of already cached requests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants