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) => queryInputArguments
queryInputArguments
fetchMoreVariable
is undefined
.fetchMoreVariable
is whatever is returned from
getFetchMore()
options
The options are identical to the options for the useQuery hook with the addition of the following:
getFetchMore: Function(lastPage, allPages) => fetchMoreVariable | Boolean
getQueryInputArguments()
[groupedQueryFunctionResults, queryExtras]
groupedQueryFunctionResults: Array<any>
[]
.queryExtras: Object
isFetching: Boolean
true
if the query is currently fetching, including
background fetching.failureCount: Integer
0
when the query succeeds.refetch()
- Function({ force, throwOnError }) => void
force: true
option and
refetch it regardless of it's freshnessthrowOnError: true
optionfetchMore()
-
Function(fetchMoreVariableOverride, { previous }) => Promise
fetchMore(nextPageVars, { previous: true })
canFetchMore: Boolean
paginated
mode, this will be true
if there is more data
to be fetched (known via the required getFetchMore
option function).setQueryData()
- Function(newData, opts) => void
newData
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()