useSubscription()
Traducción Beta No Oficial
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
El hook useSubscription permite suscribirse a un procedimiento de suscripción en el servidor.
Firma
Opciones
consejo
- Si necesitas configurar opciones pero no deseas pasar ningún input, puedes usar
undefined. - Si pasas
skipTokende@tanstack/react-query, la suscripción se pausará. - Consulta nuestro ejemplo SSE para ver un caso completo de uso de suscripciones.
tsxfunction useSubscription<TOutput, TError>(input: TInput | SkipToken,opts?: UseTRPCSubscriptionOptions<TOutput, TError>,): TRPCSubscriptionResult<TOutput, TError>;interface UseTRPCSubscriptionOptions<TOutput, TError> {/*** Callback invoked when the subscription starts.*/onStarted?: () => void;/*** Callback invoked when new data is received from the subscription.* @param data - The data received.*/onData?: (data: TOutput) => void;/*** Callback invoked when an **unrecoverable error** occurs and the subscription is stopped.*/onError?: (error: TError) => void;/*** Callback invoked when the subscription is completed.*/onComplete?: () => void;/*** @deprecated Use a `skipToken` from `@tanstack/react-query` instead.* This will be removed in a future version.*/enabled?: boolean;}
tsxfunction useSubscription<TOutput, TError>(input: TInput | SkipToken,opts?: UseTRPCSubscriptionOptions<TOutput, TError>,): TRPCSubscriptionResult<TOutput, TError>;interface UseTRPCSubscriptionOptions<TOutput, TError> {/*** Callback invoked when the subscription starts.*/onStarted?: () => void;/*** Callback invoked when new data is received from the subscription.* @param data - The data received.*/onData?: (data: TOutput) => void;/*** Callback invoked when an **unrecoverable error** occurs and the subscription is stopped.*/onError?: (error: TError) => void;/*** Callback invoked when the subscription is completed.*/onComplete?: () => void;/*** @deprecated Use a `skipToken` from `@tanstack/react-query` instead.* This will be removed in a future version.*/enabled?: boolean;}
Tipo de retorno
tstype TRPCSubscriptionResult<TOutput, TError> = {/*** The current status of the subscription.* Will be one of: `'idle'`, `'connecting'`, `'pending'`, or `'error'`.** - `idle`: subscription is disabled or ended* - `connecting`: trying to establish a connection* - `pending`: connected to the server, receiving data* - `error`: an error occurred and the subscription is stopped*/status: 'idle' | 'connecting' | 'pending' | 'error';/*** The last data received from the subscription.*/data: TOutput | undefined;/*** The last error received - will be `null` whenever the status is `'pending'` or `'idle'`* - has a value only when the status is `'error'`* - *may* have a value when the status is `'connecting'`*/error: TRPCClientError | null;/*** Function to reset the subscription.*/reset: () => void;};
tstype TRPCSubscriptionResult<TOutput, TError> = {/*** The current status of the subscription.* Will be one of: `'idle'`, `'connecting'`, `'pending'`, or `'error'`.** - `idle`: subscription is disabled or ended* - `connecting`: trying to establish a connection* - `pending`: connected to the server, receiving data* - `error`: an error occurred and the subscription is stopped*/status: 'idle' | 'connecting' | 'pending' | 'error';/*** The last data received from the subscription.*/data: TOutput | undefined;/*** The last error received - will be `null` whenever the status is `'pending'` or `'idle'`* - has a value only when the status is `'error'`* - *may* have a value when the status is `'connecting'`*/error: TRPCClientError | null;/*** Function to reset the subscription.*/reset: () => void;};
Ejemplo
components/MyComponent.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {const [numbers, setNumbers] = React.useState<number[]>([]);const result = trpc.onNumber.useSubscription(undefined, {onData: (num) => {setNumbers((prev) => [...prev, num]);},});return (<div><h1>Subscription Example</h1><p>{result.status}: <pre>{JSON.stringify(result.data, null, 2)}</pre></p><h2>Previous numbers:</h2><ul>{numbers.map((num, i) => (<li key={i}>{num}</li>))}</ul>{result.status === 'error' && (<button onClick={() => result.reset()}>Something went wrong - restart the subscription</button>)}</div>);}
components/MyComponent.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {const [numbers, setNumbers] = React.useState<number[]>([]);const result = trpc.onNumber.useSubscription(undefined, {onData: (num) => {setNumbers((prev) => [...prev, num]);},});return (<div><h1>Subscription Example</h1><p>{result.status}: <pre>{JSON.stringify(result.data, null, 2)}</pre></p><h2>Previous numbers:</h2><ul>{numbers.map((num, i) => (<li key={i}>{num}</li>))}</ul>{result.status === 'error' && (<button onClick={() => result.reset()}>Something went wrong - restart the subscription</button>)}</div>);}