Aller au contenu principal
Version : 10.x

useInfiniteQuery

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 →

info
  • Votre procédure doit accepter une entrée cursor de n'importe quel type (string, number, etc.) pour exposer ce hook.
  • Pour plus de détails sur les requêtes infinies, consultez la documentation de react-query
  • Dans cet exemple nous utilisons Prisma - voir leur documentation sur la pagination par curseur

Exemple de procédure

server/routers/_app.ts
tsx
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
import { Context } from './[trpc]';
export const t = initTRPC.create();
export const appRouter = t.router({
infinitePosts: t.procedure
.input(
z.object({
limit: z.number().min(1).max(100).nullish(),
cursor: z.number().nullish(), // <-- "cursor" needs to exist, but can be any type
}),
)
.query(async (opts) => {
const { input } = opts;
const limit = input.limit ?? 50;
const { cursor } = input;
const items = await prisma.post.findMany({
take: limit + 1, // get an extra item at the end which we'll use as next cursor
where: {
title: {
contains: 'Prisma' /* Optional filter */,
},
},
cursor: cursor ? { myCursor: cursor } : undefined,
orderBy: {
myCursor: 'asc',
},
});
let nextCursor: typeof cursor | undefined = undefined;
if (items.length > limit) {
const nextItem = items.pop();
nextCursor = nextItem!.myCursor;
}
return {
items,
nextCursor,
};
}),
});
server/routers/_app.ts
tsx
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
import { Context } from './[trpc]';
export const t = initTRPC.create();
export const appRouter = t.router({
infinitePosts: t.procedure
.input(
z.object({
limit: z.number().min(1).max(100).nullish(),
cursor: z.number().nullish(), // <-- "cursor" needs to exist, but can be any type
}),
)
.query(async (opts) => {
const { input } = opts;
const limit = input.limit ?? 50;
const { cursor } = input;
const items = await prisma.post.findMany({
take: limit + 1, // get an extra item at the end which we'll use as next cursor
where: {
title: {
contains: 'Prisma' /* Optional filter */,
},
},
cursor: cursor ? { myCursor: cursor } : undefined,
orderBy: {
myCursor: 'asc',
},
});
let nextCursor: typeof cursor | undefined = undefined;
if (items.length > limit) {
const nextItem = items.pop();
nextCursor = nextItem!.myCursor;
}
return {
items,
nextCursor,
};
}),
});

Exemple de composant React

components/MyComponent.tsx
tsx
import { trpc } from '../utils/trpc';
export function MyComponent() {
const myQuery = trpc.infinitePosts.useInfiniteQuery(
{
limit: 10,
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
// initialCursor: 1, // <-- optional you can pass an initialCursor
},
);
// [...]
}
components/MyComponent.tsx
tsx
import { trpc } from '../utils/trpc';
export function MyComponent() {
const myQuery = trpc.infinitePosts.useInfiniteQuery(
{
limit: 10,
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
// initialCursor: 1, // <-- optional you can pass an initialCursor
},
);
// [...]
}

Assistants

getInfiniteData()

Cet utilitaire récupère les données actuellement en cache d'une requête infinie existante

components/MyComponent.tsx
tsx
import { trpc } from '../utils/trpc';
export function MyComponent() {
const utils = trpc.useUtils();
const myMutation = trpc.infinitePosts.add.useMutation({
async onMutate(opts) {
await utils.infinitePosts.cancel();
const allPosts = utils.infinitePosts.getInfiniteData({ limit: 10 });
// [...]
},
});
}
components/MyComponent.tsx
tsx
import { trpc } from '../utils/trpc';
export function MyComponent() {
const utils = trpc.useUtils();
const myMutation = trpc.infinitePosts.add.useMutation({
async onMutate(opts) {
await utils.infinitePosts.cancel();
const allPosts = utils.infinitePosts.getInfiniteData({ limit: 10 });
// [...]
},
});
}

setInfiniteData()

Cet utilitaire vous permet de mettre à jour les données en cache d'une requête

components/MyComponent.tsx
tsx
import { trpc } from '../utils/trpc';
export function MyComponent() {
const utils = trpc.useUtils();
const myMutation = trpc.infinitePosts.delete.useMutation({
async onMutate(opts) {
await utils.infinitePosts.cancel();
utils.infinitePosts.setInfiniteData({ limit: 10 }, (data) => {
if (!data) {
return {
pages: [],
pageParams: [],
};
}
return {
...data,
pages: data.pages.map((page) => ({
...page,
items: page.items.filter((item) => item.status === 'published'),
})),
};
});
},
});
// [...]
}
components/MyComponent.tsx
tsx
import { trpc } from '../utils/trpc';
export function MyComponent() {
const utils = trpc.useUtils();
const myMutation = trpc.infinitePosts.delete.useMutation({
async onMutate(opts) {
await utils.infinitePosts.cancel();
utils.infinitePosts.setInfiniteData({ limit: 10 }, (data) => {
if (!data) {
return {
pages: [],
pageParams: [],
};
}
return {
...data,
pages: data.pages.map((page) => ({
...page,
items: page.items.filter((item) => item.status === 'published'),
})),
};
});
},
});
// [...]
}