1
1
"use client" ;
2
2
3
- import { QueryClientProvider , type QueryClient } from "@tanstack/react-query" ;
4
- import { httpBatchStreamLink , loggerLink } from "@trpc/client" ;
5
- import { createTRPCReact } from "@trpc/react-query" ;
3
+ import {
4
+ isServer ,
5
+ QueryClientProvider ,
6
+ type QueryClient ,
7
+ } from "@tanstack/react-query" ;
8
+ import {
9
+ createTRPCClient ,
10
+ httpBatchStreamLink ,
11
+ loggerLink ,
12
+ } from "@trpc/client" ;
6
13
import { type inferRouterInputs , type inferRouterOutputs } from "@trpc/server" ;
14
+ import { createTRPCContext } from "@trpc/tanstack-react-query" ;
7
15
import { useState } from "react" ;
8
16
import SuperJSON from "superjson" ;
9
17
@@ -12,17 +20,23 @@ import { createQueryClient } from "./query-client";
12
20
13
21
let clientQueryClientSingleton : QueryClient | undefined = undefined ;
14
22
const getQueryClient = ( ) => {
15
- if ( typeof window === "undefined" ) {
23
+ if ( isServer ) {
16
24
// Server: always make a new query client
17
25
return createQueryClient ( ) ;
18
26
}
19
- // Browser: use singleton pattern to keep the same query client
27
+ // Browser: make a new query client if we don't already have one
28
+ // This is very important, so we don't re-make a new client if React
29
+ // suspends during the initial render. This may not be needed if we
30
+ // have a suspense boundary BELOW the creation of the query client
20
31
clientQueryClientSingleton ??= createQueryClient ( ) ;
21
32
22
33
return clientQueryClientSingleton ;
23
34
} ;
24
35
25
- export const api = createTRPCReact < AppRouter > ( ) ;
36
+ const api = createTRPCContext < AppRouter > ( ) ;
37
+
38
+ export const useTRPC = api . useTRPC ;
39
+ export const useTRPCClient = api . useTRPCClient ;
26
40
27
41
/**
28
42
* Inference helper for inputs.
@@ -42,7 +56,7 @@ export function TRPCReactProvider(props: { children: React.ReactNode }) {
42
56
const queryClient = getQueryClient ( ) ;
43
57
44
58
const [ trpcClient ] = useState ( ( ) =>
45
- api . createClient ( {
59
+ createTRPCClient < AppRouter > ( {
46
60
links : [
47
61
loggerLink ( {
48
62
enabled : ( op ) =>
@@ -64,9 +78,9 @@ export function TRPCReactProvider(props: { children: React.ReactNode }) {
64
78
65
79
return (
66
80
< QueryClientProvider client = { queryClient } >
67
- < api . Provider client = { trpcClient } queryClient = { queryClient } >
81
+ < api . TRPCProvider trpcClient = { trpcClient } queryClient = { queryClient } >
68
82
{ props . children }
69
- </ api . Provider >
83
+ </ api . TRPCProvider >
70
84
</ QueryClientProvider >
71
85
) ;
72
86
}
0 commit comments