provider.tsx44 lines, 1.1 KB
| 1 | "use client"; |
| 2 | |
| 3 | import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; |
| 4 | import { httpBatchLink } from "@trpc/client"; |
| 5 | import { useState } from "react"; |
| 6 | import superjson from "superjson"; |
| 7 | import { trpc } from "./client"; |
| 8 | |
| 9 | function getBaseUrl() { |
| 10 | if (typeof window !== "undefined") return ""; |
| 11 | if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; |
| 12 | return `http://localhost:${process.env.PORT ?? 3000}`; |
| 13 | } |
| 14 | |
| 15 | export function TRPCProvider({ children }: { children: React.ReactNode }) { |
| 16 | const [queryClient] = useState( |
| 17 | () => |
| 18 | new QueryClient({ |
| 19 | defaultOptions: { |
| 20 | queries: { |
| 21 | staleTime: 5 * 1000, |
| 22 | refetchOnWindowFocus: false, |
| 23 | }, |
| 24 | }, |
| 25 | }), |
| 26 | ); |
| 27 | |
| 28 | const [trpcClient] = useState(() => |
| 29 | trpc.createClient({ |
| 30 | links: [ |
| 31 | httpBatchLink({ |
| 32 | url: `${getBaseUrl()}/api/trpc`, |
| 33 | transformer: superjson, |
| 34 | }), |
| 35 | ], |
| 36 | }), |
| 37 | ); |
| 38 | |
| 39 | return ( |
| 40 | <trpc.Provider client={trpcClient} queryClient={queryClient}> |
| 41 | <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> |
| 42 | </trpc.Provider> |
| 43 | ); |
| 44 | } |