urql-graphql / urql

The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
https://urql.dev/goto/docs
MIT License
8.57k stars 444 forks source link

Suggestion: docs(nextjs): The example using client components should delcare `client` and `ssr` inside the function component instead of outside it. #3367

Closed natekfl closed 11 months ago

natekfl commented 11 months ago

In the docs for Next.js SSR, there is this example:

// app/client/layout.tsx
'use client';

import { UrqlProvider, ssrExchange, cacheExchange, fetchExchange, createClient } from '@urql/next';

const ssr = ssrExchange();
const client = createClient({
  url: 'https://trygql.formidable.dev/graphql/web-collections',
  exchanges: [cacheExchange, ssr, fetchExchange],
  suspense: true,
});

export default function Layout({ children }: React.PropsWithChildren) {
  return (
    <UrqlProvider client={client} ssr={ssr}>
      {children}
    </UrqlProvider>
  );
}

However, as written, the server develops a cache across requests, since ssr and client are declared outside of any react component. These should be moved to inside of the component, so that a new client is used for each new request on the server side.

// app/client/layout.tsx
'use client';

import { UrqlProvider, ssrExchange, cacheExchange, fetchExchange, createClient } from '@urql/next';

export default function Layout({ children }: React.PropsWithChildren) {

  const ssr = ssrExchange();
  const client = createClient({
    url: 'https://trygql.formidable.dev/graphql/web-collections',
    exchanges: [cacheExchange, ssr, fetchExchange],
    suspense: true,
  });

  return (
    <UrqlProvider client={client} ssr={ssr}>
      {children}
    </UrqlProvider>
  );
}

(I may also be misunderstanding something around ssr, and if that's the case please let me know. However when I followed the docs as listed, I ran into caching issues)

JoviDeCroock commented 11 months ago

That is a very good point, we should move that to a useMemo as well I suppose 😅 the most important one in this case would be to re-create the ssrExchange as that would be the one persisting data across invocations if the server lives for multiple requests.