Simplest useInfiniteQuery implementation?
I'm trying to enable
Then:
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()
}),
const { data: vendors = [] } = api.accounts.vendors.useQuery({})
const { data: vendors = [] } = api.accounts.vendors.useQuery({})
Solution:Jump to solution
I got it to work!
```ts
vendors: protectedProcedure
.input(z.object({
take: z.number().default(10),...
1 Reply
Solution
I got it to work!
And
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,
}
}),
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) ?? []