npm.io
11.29.5 • Published yesterday

@trpc/react-query

Licence
MIT
Version
11.29.5
Deps
0
Size
591 kB
Vulns
0
Weekly
0
Stars
40.7K
DeprecatedThis package is deprecated

tRPC

tRPC

End-to-end typesafe APIs made easy

Demo

@trpc/react-query

A tRPC wrapper around react-query.

@trpc/react-query is deprecated. It only gets bug fixes and will be removed in the next major version of tRPC. Use @trpc/tanstack-react-query instead. To move an existing project, follow the migration guide.

Documentation

Full documentation for @trpc/react-query can be found here

Installation

# npm
npm install @trpc/react-query @tanstack/react-query

# Yarn
yarn add @trpc/react-query @tanstack/react-query

# pnpm
pnpm add @trpc/react-query @tanstack/react-query

# Bun
bun add @trpc/react-query @tanstack/react-query

Basic Example

Create a utils file that exports tRPC hooks and providers.

import { createTRPCReact } from '@trpc/react-query';
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 { trpc } from '~/utils/trpc';
import React, { useState } from 'react';

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 { trpc } from '~/utils/trpc';

export function Hello() {
  const { data, error, status } = trpc.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>;
}

Sponsors

If you enjoy working with tRPC and want to support us, consider giving a token appreciation by GitHub Sponsors!

tRPC's sponsors, each drawn bigger the more they've given

Silver partners
CodeRabbit
CodeRabbit
Greptile
Greptile
SerpApi
SerpApi
Backers
Unkey
Unkey
Dr. B
Dr. B
Ryan Magoon
Ryan Magoon
Proxidize
Proxidize
Liminity AB
Liminity AB
BestKru
BestKru
Max Greenwald
Max Greenwald
Dmitry Maykov
Dmitry Maykov
Chris Bradley
Chris Bradley
fanvue
fanvue
Aerius Ventilation AB
Aerius Ventilation AB
Stefan Smiljkovic
Stefan Smiljkovic
Kalle
Kalle
Drizzle Team
Drizzle Team
Spencer McKenney
Spencer McKenney
Andrei Karushev
Andrei Karushev
Venue.ink
Venue.ink
Vault
Vault