useInfiniteQuery
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
- Tu procedimiento debe aceptar una entrada
cursorde tipoany - Para más detalles sobre consultas infinitas, lee la documentación de react-query
- En este ejemplo usamos Prisma - consulta su documentación sobre paginación basada en cursor
Procedimiento de ejemplo
server/routers/_app.tstsximport * as trpc from '@trpc/server';import { Context } from './[trpc]';import { z } from 'zod';export const appRouter = trpc.router<Context>().query('infinitePosts', {input: z.object({limit: z.number().min(1).max(100).nullish(),cursor: z.number().nullish(), // <-- "cursor" needs to exist, but can be any type}),async resolve({ input }) {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 cursorwhere: {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.tstsximport * as trpc from '@trpc/server';import { Context } from './[trpc]';import { z } from 'zod';export const appRouter = trpc.router<Context>().query('infinitePosts', {input: z.object({limit: z.number().min(1).max(100).nullish(),cursor: z.number().nullish(), // <-- "cursor" needs to exist, but can be any type}),async resolve({ input }) {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 cursorwhere: {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,};})
Componente React de ejemplo
components/MyComponent.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {const myQuery = trpc.useInfiniteQuery(['infinitePosts',{limit: 10,},],{getNextPageParam: (lastPage) => lastPage.nextCursor,},);// [...]}
components/MyComponent.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {const myQuery = trpc.useInfiniteQuery(['infinitePosts',{limit: 10,},],{getNextPageParam: (lastPage) => lastPage.nextCursor,},);// [...]}
Utilidades
getInfiniteQueryData()
Esta función auxiliar obtiene los datos actualmente almacenados en caché de una consulta infinita existente
components/MyComponent.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {const utils = trpc.useContext();const myMutation = trpc.useMutation('infinitePosts.add', {onMutate({ post }) {await utils.cancelQuery(['infinitePosts']);const allPosts = utils.getInfiniteQueryData(['infinitePosts', { limit: 10 }]);// [...]}})}
components/MyComponent.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {const utils = trpc.useContext();const myMutation = trpc.useMutation('infinitePosts.add', {onMutate({ post }) {await utils.cancelQuery(['infinitePosts']);const allPosts = utils.getInfiniteQueryData(['infinitePosts', { limit: 10 }]);// [...]}})}
setInfiniteQueryData()
Esta función auxiliar te permite actualizar los datos almacenados en caché de una consulta
components/MyComponent.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {const utils = trpc.useContext();const myMutation = trpc.useMutation('infinitePosts.delete', {onMutate({ post }) {await utils.cancelQuery(['infinitePosts']);utils.setInfiniteQueryData(['infinitePosts', { 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.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {const utils = trpc.useContext();const myMutation = trpc.useMutation('infinitePosts.delete', {onMutate({ post }) {await utils.cancelQuery(['infinitePosts']);utils.setInfiniteQueryData(['infinitePosts', { limit: 10 }], (data) => {if (!data) {return {pages: [],pageParams: []}}return {...data,pages: data.pages.map((page) => {...page,items: page.items.filter((item) => item.status === 'published')})}});}});// [...]}