Simplest useInfiniteQuery implementation?

I'm trying to enable useInfiniteQuery on a tRPC query. I saw several tutorials, but it looked very different every time. My current setup looks something like:
vendors: protectedProcedure
.input(z.object({
take: z.number().default(10),
cursor: z.number().nullish(),
}))
.query(async ({ ctx: { prisma }, input: { take, cursor } }) => {
type Vendor = { vendor_id: string }

return prisma.$queryRaw<Vendor[]>`
select vendor_id
from vendor
limit ${take}
offset 0`
// how to use cursor here? ^
// not using .findMany()
}),
vendors: protectedProcedure
.input(z.object({
take: z.number().default(10),
cursor: z.number().nullish(),
}))
.query(async ({ ctx: { prisma }, input: { take, cursor } }) => {
type Vendor = { vendor_id: string }

return prisma.$queryRaw<Vendor[]>`
select vendor_id
from vendor
limit ${take}
offset 0`
// how to use cursor here? ^
// not using .findMany()
}),
Then:
const { data: vendors = [] } = api.accounts.vendors.useQuery({})
const { data: vendors = [] } = api.accounts.vendors.useQuery({})
Solution:
I got it to work! ```ts vendors: protectedProcedure .input(z.object({ take: z.number().default(10),...
Jump to solution
1 Reply
Solution
Mocha
Mocha2y ago
I got it to work!
vendors: protectedProcedure
.input(z.object({
take: z.number().default(10),
cursor: z.number().nullish(),
}))
.query(async ({ ctx: { prisma }, input: { take, cursor } }) => {
type Vendor = { vendor_id: string }

const vendors = prisma.$queryRaw<Vendor[]>`
select vendor_id
from vendor
where vendor_id > ${cursor ?? 0}
order by vendor_id
limit ${take}`
// cursor = table id where you wanna *start* query from
// offset works too but cursor is more efficient
return {
vendors,
nextCursor: vendors.length < take ? undefined : vendors.at(-1)?.vendor_id,
}
}),
vendors: protectedProcedure
.input(z.object({
take: z.number().default(10),
cursor: z.number().nullish(),
}))
.query(async ({ ctx: { prisma }, input: { take, cursor } }) => {
type Vendor = { vendor_id: string }

const vendors = prisma.$queryRaw<Vendor[]>`
select vendor_id
from vendor
where vendor_id > ${cursor ?? 0}
order by vendor_id
limit ${take}`
// cursor = table id where you wanna *start* query from
// offset works too but cursor is more efficient
return {
vendors,
nextCursor: vendors.length < take ? undefined : vendors.at(-1)?.vendor_id,
}
}),
And
const { data, fetchNextPage, hasNextPage } = api.accounts.vendors.useInfiniteQuery(
{ },
{
getNextPageParam: lastPage => lastPage.nextCursor,
}
)
const vendors = data?.pages.flatMap(page => page.vendors) ?? []
const { data, fetchNextPage, hasNextPage } = api.accounts.vendors.useInfiniteQuery(
{ },
{
getNextPageParam: lastPage => lastPage.nextCursor,
}
)
const vendors = data?.pages.flatMap(page => page.vendors) ?? []
Want results from more Discord servers?
Add your server