When performing pagination type queries, is there a way to determine if there are more results? I can see I can use the offset
and first
parameters but in the response it doesn’t tell me if there are any more results. Is this possible?
Does anyone have any ideas ?
Generally speaking, get the total count and subtract the offset.
J
You can do a separate block that returns the count of all and then use it to figure out if there are more still.
Let me know if you need an example
The way I solved this problem:
GraphQL query:
query PaginateParagraphs($slug: String!, $first: Int!, $offset: Int!){
paginateParagraphs(slug: $slug, first: $first, offset: $offset) {
id
speaker {
name
}
}
paginateParagraphsMetadata(slug: $slug) {
total_count
}
}
schema.graphql:
paginateParagraphs(slug: String!, first: Int!, offset: Int!): [Paragraph] @custom(dql: """
query paginateParagraphs(func: uid(paragraphs), first: $first, offset: $offset) @cascade {
id: uid
speaker: Paragraph.speaker {
name: Speaker.name
}
}
}
""")
paginateParagraphsMetadata(slug: String!): Metadata @custom(dql: """
query q($slug: string) {
var(func: type(Transcript)) @filter(eq(Transcript.slug, $slug)) {
Transcript.paragraphs {
a as count(uid)
}
}
paginateParagraphsMetadata() @normalize {
total_count : sum(val(a))
}
}
""")
As for how to determine whether there are more results, I use SvelteQuery (Based on ReactQuery), and pass in a getNextPageParam
function that calculates whether there is another page based on how many results have been fetched (no. of pages * amount of results per page), and whether this number is higher than the total_count.
const paragraphQueryResult = useInfiniteQuery('paragraphsQuery', getParagraphs, {
getNextPageParam: (lastGroup, pages) => {
const total = lastGroup.paginateParagraphsMetadata.total_count;
if (pages.length * limit >= total) {
return undefined;
} else {
return pages.length * limit
}
}
});
Let me know if any of that doesn’t make sense.