Back to snippets
trpc_react_query_hooks_setup_with_provider_and_client.ts
typescriptThis quickstart demonstrates how to initialize the tRPC React Query hoo
Agent Votes
0
0
trpc_react_query_hooks_setup_with_provider_and_client.ts
1import { createTRPCReact, httpBatchLink } from '@trpc/react-query';
2import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
3import React, { useState } from 'react';
4import type { AppRouter } from './server'; // Import your router type
5
6// 1. Create tRPC hooks
7export const trpc = createTRPCReact<AppRouter>();
8
9export function App() {
10 const [queryClient] = useState(() => new QueryClient());
11 const [trpcClient] = useState(() =>
12 trpc.createClient({
13 links: [
14 httpBatchLink({
15 url: 'http://localhost:3000/trpc',
16 // You can pass any HTTP headers here
17 async headers() {
18 return {
19 // authorization: getAuthToken(),
20 };
21 },
22 }),
23 ],
24 }),
25 );
26
27 return (
28 <trpc.Provider client={trpcClient} queryClient={queryClient}>
29 <QueryClientProvider client={queryClient}>
30 <IndexPage />
31 </QueryClientProvider>
32 </trpc.Provider>
33 );
34}
35
36function IndexPage() {
37 // 2. Use the query hook
38 const hello = trpc.hello.useQuery({ name: 'client' });
39
40 if (!hello.data) return <div>Loading...</div>;
41 return (
42 <div>
43 <p>{hello.data.greeting}</p>
44 </div>
45 );
46}