Skip to content

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

Open
@mohammadhosseinmoradi

Description

@mohammadhosseinmoradi

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions