Saltar al contenido principal
Versión: 9.x

Uso con React

Traducción Beta No Oficial

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

información
  • Si estás usando Next.js, lee la guía de Uso con Next.js en su lugar.
  • Para inferir tipos desde tu backend en Node.js, deberías tener el frontend y backend en el mismo monorepo.

Agregar tRPC a un proyecto existente de React

Lado del servidor

1. Instalar dependencias

bash
yarn add @trpc/server zod
bash
yarn add @trpc/server zod
  • Zod: la mayoría de los ejemplos usan Zod para validación de entradas y lo recomendamos encarecidamente, aunque no es obligatorio. Puedes usar una biblioteca de validación de tu elección (Yup, Superstruct, io-ts, etc). De hecho, cualquier objeto que contenga un método parse, create o validateSync funcionará.

2. Habilitar modo estricto

Si quieres usar Zod para validación de entradas, asegúrate de habilitar el modo estricto en tu tsconfig.json:

json
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strict": true
}
}
json
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strict": true
}
}

Si el modo estricto es demasiado, al menos habilita strictNullChecks:

json
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strictNullChecks": true
}
}
json
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strictNullChecks": true
}
}

3. Implementa tu appRouter

Sigue el Inicio rápido y lee la documentación de @trpc/server para orientación. Una vez que tengas tu API implementada y escuchando mediante HTTP, continúa con el siguiente paso.

Lado del cliente

¡tRPC funciona perfectamente con Create React App!

1. Instalar dependencias

bash
yarn add @trpc/client @trpc/server @trpc/react react-query@3
bash
yarn add @trpc/client @trpc/server @trpc/react react-query@3
  • @trpc/server: Esta es una dependencia peer de @trpc/client, ¡así que debes instalarla nuevamente!

  • React Query de Tanstack: @trpc/react proporciona un envoltorio ligero sobre @tanstack/react-query. Es necesario como dependencia peer.

2. Crear hooks de tRPC

Crea un conjunto de hooks de React fuertemente tipados a partir de la firma de tipos de tu AppRouter con createReactQueryHooks.

utils/trpc.ts
tsx
// utils/trpc.ts
import { createReactQueryHooks } from '@trpc/react';
import type { AppRouter } from '../path/to/router.ts';
export const trpc = createReactQueryHooks<AppRouter>();
// => { useQuery: ..., useMutation: ...}
utils/trpc.ts
tsx
// utils/trpc.ts
import { createReactQueryHooks } from '@trpc/react';
import type { AppRouter } from '../path/to/router.ts';
export const trpc = createReactQueryHooks<AppRouter>();
// => { useQuery: ..., useMutation: ...}

3. Agregar proveedores de tRPC

En tu App.tsx

App.tsx
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}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}
App.tsx
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}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}

4. Obtener datos

pages/IndexPage.tsx
tsx
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>
);
}
pages/IndexPage.tsx
tsx
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>
);
}