Package Exports
- @trpc/react
- @trpc/react/shared
- @trpc/react/ssg
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@trpc/react) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
End-to-end typesafe APIs made easy
@trpc/react
Connect a tRPC server to React.
Documentation
Full documentation for @trpc/react
can be found here
Installation
# npm
npm install @trpc/react@next @tanstack/react-query
# Yarn
yarn add @trpc/react@next @tanstack/react-query
# pnpm
pnpm add @trpc/react@next @tanstack/react-query
Basic Example
Create a utils file that exports tRPC hooks and providers.
import { createReactQueryHooks, createTRPCReact } from '@trpc/react';
import type { AppRouter } from './server';
export const trpc = createTRPCReact<AppRouter>();
Use the provider to connect to your API.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import React from 'react';
import { useState } from 'react';
import { trpc } from '~/utils/trpc';
export function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
url: 'http://localhost:5000/trpc',
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}
Now in any component, you can query your API using the proxy exported from the utils file.
import { proxy } from '~/utils/trpc';
export function Hello() {
const { data, error, status } = proxy.greeting.useQuery({ name: 'tRPC' });
if (error) {
return <p>{error.message}</p>;
}
if (status !== 'success') {
return <p>Loading...</p>;
}
return <div>{data && <p>{data.greeting}</p>}</div>;
}