www/versioned_docs/version-9.x/reactjs/introduction.md
:::info
:::
yarn add @trpc/server zod
parse, create or validateSync method will work.If you want to use Zod for input validation, make sure you have enabled strict mode in your tsconfig.json:
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strict": true
}
}
If strict mode is too much, at least enable strictNullChecks:
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strictNullChecks": true
}
}
appRouterFollow the Quickstart and read the @trpc/server docs for guidance on this. Once you have your API implemented and listening via HTTP, continue to the next step.
tRPC works fine with Create React App!
yarn add @trpc/client @trpc/server @trpc/react react-query@3
@trpc/client so you have to install it again!Create a set of strongly-typed React hooks from your AppRouter type signature with createReactQueryHooks.
// utils/trpc.ts
import { createReactQueryHooks } from '@trpc/react';
import type { AppRouter } from '../path/to/router.ts';
export const trpc = createReactQueryHooks<AppRouter>();
// => { useQuery: ..., useMutation: ...}
In your App.tsx
import React, { useState } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { trpc } from './utils/trpc';
export function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
url: 'http://localhost:5000/trpc',
// optional
headers() {
return {
authorization: getAuthCookie(),
};
},
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
</QueryClientProvider>
</trpc.Provider>
);
}
import { trpc } from '../utils/trpc';
export default function IndexPage() {
const hello = trpc.useQuery(['hello', { text: 'client' }]);
if (!hello.data) return <div>Loading...</div>;
return (
<div>
<p>{hello.data.greeting}</p>
</div>
);
}