apollographql / apollo-client-nextjs

Apollo Client support for the Next.js App Router
https://www.npmjs.com/package/@apollo/experimental-nextjs-app-support
MIT License
448 stars 35 forks source link

`registerApolloClient` should only be used in a React Server Component context error when trying to call a Server Action in a Client Component #78

Open ramivalta opened 1 year ago

ramivalta commented 1 year ago

Greetings!

I have a Server Action in a separate file that uses the getClient function described in the "In RSC" segment of the readme. As per NextJS documentation it has the 'use server' directive at the top.

I'm trying to call this action in a Client Component using the useTransition hook, but I get the "`registerApolloClient` should only be used in a React Server Component context - in Client Components, use the `ApolloNextAppProvider`!" error. As far as I understand I definitely am in the Server Component context though. If I monkey patch out the check for React.createContext in registerApolloClient.ts my code seems to function correctly.

Is this a bug or am I doing something I'm not supposed to do?

plausible-phry commented 1 year ago

Hi @ramivalta, unfortunately, Server Actions are yet another environment that is different from React Server Components. (Middleware are another, and then of course, Client Components).

I would suggest that you just call the createClient function that you are passing into registerApolloClient from your server actions - as they run in a different environment, it's impossible to share a client between RSC and SA anyways.

It might be possible in the future to use getClient in Server Actions, but at this point that's not the case.

tonnguyen commented 9 months ago

Hi @plausible-phry ,

If I want to do a query in Middleware, should I use the same approach as in Server Actions? What cache should I use, NextSSRInMemoryCache or InMemoryCache?

phryneas commented 9 months ago

@tonnguyen you're not doing SSR, so you'd use a normal InMemoryCache :) I believe by now it should also be possible to call getClient, but I'm not 100% sure on that.

tonnguyen commented 9 months ago

I got "React.cache is not a function" error when using registerApolloClient in Middleware so I guess it is not possible.

Thanks!

phryneas commented 9 months ago

@tonnguyen Good point. Yeah, then you'd just call the same createClient.