useQuery()
Traduction Bêta Non Officielle
Cette page a été traduite par PageTurner AI (bêta). Non approuvée officiellement par le projet. Vous avez trouvé une erreur ? Signaler un problème →
Les hooks fournis par
@trpc/reactsont une fine surcouche autour de React Query. Pour des informations détaillées sur les options et les modèles d'utilisation, consultez leur documentation sur les Requêtes.
tsxfunction useQuery(pathAndInput: [string, TInput?],opts?: UseTRPCQueryOptions;)
tsxfunction useQuery(pathAndInput: [string, TInput?],opts?: UseTRPCQueryOptions;)
Le premier argument est un tuple [path, input] - si input est optionnel, vous pouvez omettre la partie , input.
Vous remarquerez que vous bénéficiez de l'autocomplétion sur path et de la sécurité de type automatique sur input.
Exemple
Backend code
server/routers/_app.tstsximport * as trpc from '@trpc/server';import { z } from 'zod';export const appRouter = trpc.router()// Create procedure at path 'hello'.query('hello', {// using zod schema to validate and infer input valuesinput: z.object({text: z.string().nullish(),}).nullish(),resolve({ input }) {return {greeting: `hello ${input?.text ?? 'world'}`,};},});
server/routers/_app.tstsximport * as trpc from '@trpc/server';import { z } from 'zod';export const appRouter = trpc.router()// Create procedure at path 'hello'.query('hello', {// using zod schema to validate and infer input valuesinput: z.object({text: z.string().nullish(),}).nullish(),resolve({ input }) {return {greeting: `hello ${input?.text ?? 'world'}`,};},});
components/MyComponent.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {// input is optional, so we don't have to pass second argumentconst helloNoArgs = trpc.useQuery(['hello']);const helloWithArgs = trpc.useQuery(['hello', { text: 'client' }]);return (<div><h1>Hello World Example</h1><ul><li>helloNoArgs ({helloNoArgs.status}):{' '}<pre>{JSON.stringify(helloNoArgs.data, null, 2)}</pre></li><li>helloWithArgs ({helloWithArgs.status}):{' '}<pre>{JSON.stringify(helloWithArgs.data, null, 2)}</pre></li></ul></div>);}
components/MyComponent.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {// input is optional, so we don't have to pass second argumentconst helloNoArgs = trpc.useQuery(['hello']);const helloWithArgs = trpc.useQuery(['hello', { text: 'client' }]);return (<div><h1>Hello World Example</h1><ul><li>helloNoArgs ({helloNoArgs.status}):{' '}<pre>{JSON.stringify(helloNoArgs.data, null, 2)}</pre></li><li>helloWithArgs ({helloWithArgs.status}):{' '}<pre>{JSON.stringify(helloWithArgs.data, null, 2)}</pre></li></ul></div>);}