Saltar al contenido principal
Versión: 11.x

Suspense

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 →

información
  • Asegúrate de usar la última versión de React
  • Si usas suspense con la SSR automática de tRPC en Next.js, toda la página fallará en el servidor si una consulta falla, incluso si tienes un <ErrorBoundary />

Uso

consejo

useSuspenseQuery y useSuspenseInfiniteQuery devuelven una tupla [data, query], lo que facilita usar tus datos directamente y renombrar la variable con algo descriptivo

useSuspenseQuery()

tsx
// @filename: pages/index.tsx
import React from 'react';
import { trpc } from '../utils/trpc';
 
function PostView() {
const [post, postQuery] = trpc.post.byId.useSuspenseQuery({ id: '1' });
const post: { id: string; title: string; }
 
return <>{/* ... */}</>;
}
tsx
// @filename: pages/index.tsx
import React from 'react';
import { trpc } from '../utils/trpc';
 
function PostView() {
const [post, postQuery] = trpc.post.byId.useSuspenseQuery({ id: '1' });
const post: { id: string; title: string; }
 
return <>{/* ... */}</>;
}

useSuspenseInfiniteQuery()

tsx
// @filename: pages/index.tsx
import React from 'react';
import { trpc } from '../utils/trpc';
function PostView() {
const [{ pages }, allPostsQuery] = trpc.post.all.useSuspenseInfiniteQuery(
{},
{
getNextPageParam(lastPage) {
return lastPage.nextCursor;
},
},
);
const { isFetching, isFetchingNextPage, fetchNextPage, hasNextPage } =
allPostsQuery;
return <>{/* ... */}</>;
}
tsx
// @filename: pages/index.tsx
import React from 'react';
import { trpc } from '../utils/trpc';
function PostView() {
const [{ pages }, allPostsQuery] = trpc.post.all.useSuspenseInfiniteQuery(
{},
{
getNextPageParam(lastPage) {
return lastPage.nextCursor;
},
},
);
const { isFetching, isFetchingNextPage, fetchNextPage, hasNextPage } =
allPostsQuery;
return <>{/* ... */}</>;
}

useSuspenseQueries()

Equivalente de Suspense para useQueries().

tsx
const Component = (props: { postIds: string[] }) => {
const [posts, postQueries] = trpc.useSuspenseQueries((t) =>
props.postIds.map((id) => t.post.byId({ id })),
);
return <>{/* [...] */}</>;
};
tsx
const Component = (props: { postIds: string[] }) => {
const [posts, postQueries] = trpc.useSuspenseQueries((t) =>
props.postIds.map((id) => t.post.byId({ id })),
);
return <>{/* [...] */}</>;
};

Precarga

El rendimiento de las consultas con suspense puede mejorarse mediante la precarga de datos antes de renderizar el componente Suspense (esto a veces se denomina "renderizado mientras se carga").

nota
  • La precarga y el modelo de renderizado mientras se carga dependen mucho de tu framework y enrutador. Recomendamos leer la documentación del enrutador de tu framework junto con la documentación de @tanstack/react-query.
  • Si usas Next.js, consulta la documentación sobre Helpers del lado del servidor para implementar la precarga en el servidor.

Precarga a nivel de ruta

tsx
const utils = createTRPCQueryUtils({ queryClient, client: trpcClient });
// tanstack router/ react router loader
const loader = async (params: { id: string }) =>
utils.post.byId.ensureQueryData({ id: params.id });
tsx
const utils = createTRPCQueryUtils({ queryClient, client: trpcClient });
// tanstack router/ react router loader
const loader = async (params: { id: string }) =>
utils.post.byId.ensureQueryData({ id: params.id });

Precarga a nivel de componente con usePrefetchQuery

tsx
import { trpc } from '../utils/trpc';
function PostViewPage(props: { postId: string }) {
trpc.post.byId.usePrefetchQuery({ id: props.postId });
return (
<Suspense>
<PostView postId={props.postId} />
</Suspense>
);
}
tsx
import { trpc } from '../utils/trpc';
function PostViewPage(props: { postId: string }) {
trpc.post.byId.usePrefetchQuery({ id: props.postId });
return (
<Suspense>
<PostView postId={props.postId} />
</Suspense>
);
}

Precarga a nivel de componente con usePrefetchInfiniteQuery

tsx
import { trpc } from '../utils/trpc';
// will have to be passed to the child PostView `useSuspenseInfiniteQuery`
export const getNextPageParam = (lastPage) => lastPage.nextCursor;
function PostViewPage(props: { postId: string }) {
trpc.post.all.usePrefetchInfiniteQuery({}, { getNextPageParam });
return (
<Suspense>
<PostView postId={props.postId} />
</Suspense>
);
}
tsx
import { trpc } from '../utils/trpc';
// will have to be passed to the child PostView `useSuspenseInfiniteQuery`
export const getNextPageParam = (lastPage) => lastPage.nextCursor;
function PostViewPage(props: { postId: string }) {
trpc.post.all.usePrefetchInfiniteQuery({}, { getNextPageParam });
return (
<Suspense>
<PostView postId={props.postId} />
</Suspense>
);
}