Skip to content

QueryConfigs are not applied when prefetching in NextJS SSR #963

@alfrescian

Description

@alfrescian

I'm trying to prefetch some queries in App.getInitialProps (nextJS SSR). my assumption is, that even when the query is prefetched on SSR the default behaviors like refetchOnWindowFocus should be working as w/o any pre-fetching.

my _app.js

import { ReactQueryDevtools } from "react-query-devtools";
import { ReactQueryCacheProvider, makeQueryCache } from "react-query";
import { Hydrate, dehydrate } from "react-query/hydration";

import { getPosts } from "../hooks/usePosts";

const MyApp = ({ Component, pageProps }) => {
  return (
    <ReactQueryCacheProvider>
      <Hydrate state={pageProps.dehydratedState}>
        <Component {...pageProps} />
        <ReactQueryDevtools initialIsOpen position="bottom-left" />
      </Hydrate>
    </ReactQueryCacheProvider>
  );
};

MyApp.getInitialProps = async () => {
  const queryCache = makeQueryCache();
  await queryCache.prefetchQuery("posts", getPosts);

  return { pageProps: { dehydratedState: dehydrate(queryCache) } };
};

export default MyApp;

my fetcher/hook:

import { useQuery } from "react-query";
import axios from "axios";

export const getPosts = async () => {
  const { data } = await axios.get(
    "https://jsonplaceholder.typicode.com/posts"
  );
  return data;
};

export default function usePosts() {
  return useQuery("posts", getPosts);
}

I've created a codesandbox: https://codesandbox.io/s/distracted-pond-h45px
the posts are not refetched when the window gains focus again.

Also, when trying to set some queryConfigs like staleTime, then these queryConfig is not used, devtools are still showing staleTime=0:

export default function usePosts() {
  return useQuery("posts", getPosts, { staleTime: 30 });
}

Also trying to set the staleTime as config on prefetchQuery does not work:

MyApp.getInitialProps = async () => {
  const queryCache = makeQueryCache();
  await queryCache.prefetchQuery("posts", getPosts, {staleTime: 30});

  return { pageProps: { dehydratedState: dehydrate(queryCache) } };
};

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