@trpc/react-query
TypeScript icon, indicating that this package has built-in type declarations

10.45.2 • Public • Published

tRPC

tRPC

End-to-end typesafe APIs made easy

Demo

@trpc/react-query

A tRPC wrapper around react-query.

Documentation

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

Installation

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

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

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

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

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>;
}

Readme

Keywords

none

Package Sidebar

Install

npm i @trpc/react-query

Homepage

trpc.io

Weekly Downloads

414,743

Version

10.45.2

License

MIT

Unpacked Size

285 kB

Total Files

114

Last publish

Collaborators

  • sachinraja
  • katt
  • juliusmarminge