useQuery()

The hooks provided by @trpc/react are a thin wrapper around React Query. For in-depth information about options and usage patterns, refer to their docs on Queries.

  1. function useQuery(
  2. pathAndInput: [string, TInput?],
  3. opts?: UseTRPCQueryOptions;
  4. )

The first argument is a [path, input]-tuple - if the input is optional, you can omit the , input-part.

You’ll notice that you get autocompletion on the path and automatic typesafety on the input.

Example

Backend code

  1. import * as trpc from '@trpc/server';
  2. import { z } from 'zod';
  3. trpc
  4. .router()
  5. // Create procedure at path 'hello'
  6. .query('hello', {
  7. // using zod schema to validate and infer input values
  8. input: z
  9. .object({
  10. text: z.string().nullish(),
  11. })
  12. .nullish(),
  13. resolve({ input }) {
  14. return {
  15. greeting: `hello ${input?.text ?? 'world'}`,
  16. };
  17. },
  18. });
  1. import { trpc } from '../utils/trpc';
  2. export function MyComponent() {
  3. // input is optional, so we don't have to pass second argument
  4. const helloNoArgs = trpc.useQuery(['hello']);
  5. const helloWithArgs = trpc.useQuery(['hello', { text: 'client' }]);
  6. return (
  7. <div>
  8. <h1>Hello World Example</h1>
  9. <ul>
  10. <li>
  11. helloNoArgs ({helloNoArgs.status}):{' '}
  12. <pre>{JSON.stringify(helloNoArgs.data, null, 2)}</pre>
  13. </li>
  14. <li>
  15. helloWithArgs ({helloWithArgs.status}):{' '}
  16. <pre>{JSON.stringify(helloWithArgs.data, null, 2)}</pre>
  17. </li>
  18. </ul>
  19. </div>
  20. );
  21. }