alerdenisov
alerdenisov2mo ago

Hello again, do convex have any examples

Hello again, do convex have any examples with NextJS, @tanstack/react-query and prefetching on a server? I'm getting error from convex/react:
@v1/app:dev: ⨯ createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component
@v1/app:dev: at eval (webpack-internal:///(rsc)/../../node_modules/convex/dist/esm/react/client.js:321:58)
@v1/app:dev: ⨯ createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component
@v1/app:dev: at eval (webpack-internal:///(rsc)/../../node_modules/convex/dist/esm/react/client.js:321:58)
8 Replies
alerdenisov
alerdenisovOP2mo ago
function getServerQueryClient() {
const convexQueryClient = new ConvexQueryClient(env.NEXT_PUBLIC_CONVEX_URL);
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60,
queryKeyHashFn: convexQueryClient.hashFn(),
queryFn: convexQueryClient.queryFn(),
},
},
});
convexQueryClient.connect(queryClient);

return queryClient;
}
function getServerQueryClient() {
const convexQueryClient = new ConvexQueryClient(env.NEXT_PUBLIC_CONVEX_URL);
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60,
queryKeyHashFn: convexQueryClient.hashFn(),
queryFn: convexQueryClient.queryFn(),
},
},
});
convexQueryClient.connect(queryClient);

return queryClient;
}
ballingt
ballingt2mo ago
In Next.js any useQuery using a Convex function needs to be in a client component, regardless of whether it's used with React Query or not.
alerdenisov
alerdenisovOP2mo ago
Okay. Can I use queryClient.setQueryData together with prefetchQuery? See only one obstacle is hashFn used for queryKey. But accordingly to source code implementation isn't complex
ballingt
ballingt2mo ago
Yeah you can! You can export that hashFn too Would love to see an example, we could use one in the https://github.com/get-convex/convex-react-query repo
alerdenisov
alerdenisovOP2mo ago
I managed to implement prefetched @tanstack/react-queries with nextjs! I would love to share some minimal example code, do you have dedicated repo for examples to make PR?
alerdenisov
alerdenisovOP2mo ago
fully working code with convex-auth, nextjs and tanstack query.
No description
alerdenisov
alerdenisovOP2mo ago
w/o any changes on client side — pure convex + react-query approach from docs
No description
ballingt
ballingt2mo ago
On option is an example in the convex-react-query repo

Did you find this page helpful?