1

In my project I'm using NextJs and tRPC for backend calls. I wanted to fetch some data in getServerSideProps using tRPC and provide it in Page component, also using react-query state for whole application. Here's my _app withTRPC config

export default withTRPC<AppRouter>({
  config({ ctx }) {
    const url = `${getBaseUrl()}/api/trpc`;
    return {
      url,
      transformer: superjson,
      queryClientConfig: { defaultOptions: { queries: { staleTime: 60 } } },
    };
  },
  ssr: false,
})(MyApp);

I used ssr: false because of 'bug' in NextJs, which will cause to return empty props for first render, if set to true.

Here's my getServerSideProps function on the page

export const getServerSideProps = async () => {
  const ssg = createSSGHelpers({
    router: appRouter,
    ctx: await createContext(),
    transformer: superjson,
  });

  const entryRD = await getPageBySlug(option.some("trados"))();
  await ssg.prefetchQuery("contentful.getProductList");

  console.log("==>props", entryRD, ssg.dehydrate());

  return {
    props: {
      trpcState: ssg.dehydrate(),
      entryRD,
    },
  };
};

When I log to the console on server, both values are there, entryRD and ssg.dehydrate(). The latter contains object with mutations and queries and also data with correctly fetched data. Here is my page code:

const Page = ({ entryRD, trpcState }: InferGetServerSidePropsType<typeof getServerSideProps>) => {
  const { data, isLoading } = trpc.useQuery(["contentful.getProductList"]);

  console.log("==>data", data, isLoading);
  return isLoading ? <div>Loading...</div> : <EntryCompontn entry={entryRD} />

When I read the docs, I understand it like:

  • fetch data on server,
  • use ssg.dehydrate() to return cache to component
  • when you use trpc.useQueried(), it will return cached value from state

Unfortunately data is empty and isLoading is true for a brief moment, when data is fetched. Did I misunderstood something, or did I make a mistake?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Zenek Wiaderko
  • 392
  • 2
  • 14

0 Answers0