Skip to content
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

useSWR not back to fallback data after switching key to fallback key when keepPreviousData is true #3034

Open
mohammadhosseinmoradi opened this issue Oct 31, 2024 · 2 comments

Comments

@mohammadhosseinmoradi
Copy link

mohammadhosseinmoradi commented Oct 31, 2024

Bug report

Description / Observed Behavior

When provide SWRConfig fallback key with unstable_serialize in SSR Mode, and use useSWR with keepPreviousData: true and revalidateIfStale: false; when change key, new data feched and everythings is okay, but when back to fallback key that provided before with SWRConfig, useSWR not back to fallback data. This happens only when keepPreviousData is true.

Expected Behavior

When change key must be return data if there otherwise fetch new data or revlidate data with key.

Repro Steps / Code Example

  // ./page.tsx

  const key = getBlogKey(parseUrlSearchParamsToGetBlogParams(urlSearchParams));
  const result = await getBlog(key);

  return (
    <SWRConfig
      value={{
        fallback: {
          [unstable_serialize(key)]: result,
        },
      }}
    >
      <Blog />
    </SWRConfig>
  );
export function useGetBlog(key: ReturnType<typeof getBlogKey>) {
  return useSWR(key, getBlog, {
    keepPreviousData: true,
    revalidateIfStale: false,
  });
}
  // ./blog.tsx

  const {
    data: blog,
    error,
    isLoading,
  } = useGetBlog(getBlogKey(parseUrlSearchParamsToGetBlogParams(searchParams)));

Fixed temporary when mutate for first time:

  useEffect(() => {
    if (!fallback[unstable_serialize(key)]) return;
    void mutate(fallback[unstable_serialize(key)], {
      revalidate: false,
    });
  }, []);

Additional Context

SWR v2.2.5

@markuskullberg-sanoma
Copy link

I ran into the same problem with 2 small differences:

  1. Not using unstable_serialize
  2. Passing the fallback option directly to useSWR() instead of <SWRConfig />

The mutate hack worked for me as well.

@markuskullberg-sanoma
Copy link

Here's a repro: https://codesandbox.io/p/sandbox/2ygdsq

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