import {useInfiniteQuery} from "blitz"
import getProjectsInfinite from "app/projects/queries/getProjectsInfinite"
function Projects(props) {
const [
groupedProjects,
{isFetching, isFetchingMore, fetchMore, canFetchMore},
] = useInfiniteQuery(
getProjectsInfinite,
(page = {take: 3, skip: 0}) => page,
{
getFetchMore: (lastGroup) => lastGroup.nextPage,
},
)
return (
<>
{groupedProjects.map((group, i) => (
<React.Fragment key={i}>
{group.projects.map((project) => (
<p key={project.id}>{project.name}</p>
))}
</React.Fragment>
))}
<div>
<button
onClick={() => fetchMore()}
disabled={!canFetchMore || !!isFetchingMore}
>
{isFetchingMore
? "Loading more..."
: canFetchMore
? "Load More"
: "Nothing more to load"}
</button>
</div>
<div>{isFetching && !isFetchingMore ? "Fetching..." : null}</div>
</>
)
}And here's the query to work with that:
export default async function getProjectsInfinite({
where,
orderBy,
take,
skip,
}: GetProjectsInfiniteInput) {
const projects = await db.project.findMany({
where,
orderBy,
take,
skip,
})
const count = await db.project.count()
const hasMore = skip! + take! < count
const nextPage = hasMore ? {take, skip: skip! + take!} : null
return {
projects,
nextPage,
}
}const [
groupedQueryFunctionResults,
{
isFetching,
failureCount,
refetch,
fetchMore,
canFetchMore,
setQueryData,
}
] = useQuery(queryResolver, getQueryInputArguments, {
getFetchMore: (lastPage, allPages) => fetchMoreVariable
...queryOptions,
})queryResolver: A Blitz query resolvergetQueryInputArguments: (fetchMoreVariable) => queryInputArgumentsqueryInputArgumentsfetchMoreVariable is undefined.fetchMoreVariable is whatever is returned from
getFetchMore()optionsThe options are identical to the options for the useQuery hook with the addition of the following:
getFetchMore: Function(lastPage, allPages) => fetchMoreVariable | BooleangetQueryInputArguments()[groupedQueryFunctionResults, queryExtras]
groupedQueryFunctionResults: Array<any>[].queryExtras: ObjectisFetching: Booleantrue if the query is currently fetching, including
background fetching.failureCount: Integer0 when the query succeeds.refetch() - Function({ force, throwOnError }) => voidforce: true option and
refetch it regardless of it's freshnessthrowOnError: true optionfetchMore() -
Function(fetchMoreVariableOverride, { previous }) => PromisefetchMore(nextPageVars, { previous: true })canFetchMore: Booleanpaginated mode, this will be true if there is more data
to be fetched (known via the required getFetchMore option function).setQueryData() - Function(newData, opts) => voidnewData can be an object of new data or a function that receives the
old data and returns the new datarefetch() to
ensure the data is correct. Disable refetch by passing an options
object {refetch: false} as the second argument.setQueryData()