Infinite queries
Page through a list, and load more pages on demand.
A feed or a long list loads one page at a time, with a "Load more" button
or infinite scroll. An infinite query holds every page loaded so far, with
the param each was fetched with, as an InfiniteQuery.InfiniteData:
{ pages, pageParams }. This page shows how to page through an endpoint
or any Effect, how pages load, and how to show them in a component.
The examples import api.ts and todos.ts from
Getting started.
Page through an endpoint
api.infiniteQuery pages through an Effetch endpoint. pageParam names
the query field each page's param is sent in:
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "./todos.js";
const = .({
: .(
.({ : ., : . }),
),
: .(.),
});
export const = .(
.("GET /activity", { : }),
{
// Sent as ?cursor=…, and left out of the key.
: "cursor",
: null as string | null,
// null or undefined: there's no next page.
: () => .,
},
);
// activity({ query: { team: "web" } }) loads its first page from
// GET /activity?team=web, and the next from ?team=web&cursor=…Every page of one call belongs to one query, since the page field is left out of the key. A few rules follow:
- the page field is set on every page's request, over any value the call gives for it;
- the param must be a value a query field takes, such as a string or a number;
- if the endpoint has a
queryschema,pageParamnames one of its optional fields whose type takes the param, so a call can leave it out.
An endpoint with an output makes infinite queries that cross to the
browser in server rendering with no schema to write, as api.query's
do.
Page through any Effect
InfiniteQuery.make defines one infinite query, and
InfiniteQuery.family one per argument. Their run fetches one page from
its param; a family's takes the member's argument first. This one loads
todos by offset, in both directions:
import * as from "effect/Schema";
import { } from "@monarcode/effetch-query";
import { , } from "./api.js";
const = .({
: .(),
: .,
: .,
: .,
});
export const = .({
: ["todos", "pages"],
: 0,
// The member's argument, then the page's param.
: (: number, ) =>
.(() =>
.("/todos", { : { , }, : }),
),
: () =>
. + . < . ? . + . : ,
// Lets the list load pages before the first, and reload dropped ones.
: () =>
. > 0 ? .(0, . - .) : ,
: 10,
// How each page crosses to the browser, and how entities find records in it.
: { : },
});
// todoPages(20) is the infinite query keyed ["todos", "pages", 20]Both nextPageParam and previousPageParam are
InfiniteQuery.PageParamFunction functions. Each gets a page, every page,
that page's param and every param, and returns undefined or null when
there's no page in that direction.
With make and family, give schema a page schema to render on the
server, and an error schema to send failures too. The page params go as
they are, so they must be JSON values (strings, numbers, booleans,
null), unless schema.pageParam gives their schema.
How pages load
The first fetch loads one page, from initialPageParam. fetchNextPage
adds the page after the last one, and fetchPreviousPage the page before
the first. You call them from useInfiniteQuery, or as
InfiniteQuery.fetchNextPage in Effect code:
- When there's no next page,
fetchNextPagereturns the loaded pages without fetching.fetchPreviousPagedoes the same, and withoutpreviousPageParamthere's never a previous page. - Called when the query has no data, it's the query's first fetch, and joins that fetch if it's already running. When a write left no pages, it fetches from the first page.
- A page that fails keeps the loaded pages: the result is a
FailurewhosepreviousSuccessstill holds them. - Past
maxPages, a page is dropped from the far end: the first when a next page loads, the last when a previous page does. - While the next page is loading, another
fetchNextPagejoins that fetch. While any other fetch of the query is in progress, it waits for it, then fetches its page. - A write made while a page loads stays: the page is added to the data shown when it lands.
A refetch is any other fetch: after an invalidation, on focus, or when a
component starts using the query while it's stale. It fetches as many
pages as are loaded, one after the other, so a list that changed
underneath doesn't show duplicates or gaps. The first page is fetched from
its stored param, which may not be initialPageParam after maxPages
dropped the first page, and each later one from nextPageParam of the page
before. The refetch stops early when there's no next page.
Fetch a page in Effect code
In Effect code, InfiniteQuery.fetchNextPage and
InfiniteQuery.fetchPreviousPage return the updated
{ pages, pageParams }, and fail with the query's error if the page
fails:
import * as from "effect/Effect";
import { } from "@monarcode/effetch-query";
import { } from "./activity.js";
export const = .(
.(({ : { : "web" } })),
() => ..(() => .),
);An infinite query is a query: invalidation,
the cache functions and the client's defaults work on it
as on any other. To change its pages in an
optimistic update, Query.update the whole
{ pages, pageParams } value; on a family, Query.update writes every
cached member. Entities find a record in every
loaded page.
Infinite query options
An infinite query takes the following options. The paging ones, from
initialPageParam to maxPages, are its InfiniteQuery.PageOptions:
| Option | What it does |
|---|---|
pageParam | The query field each page's param is sent in. api.infiniteQuery only. |
initialPageParam | The first page's param. |
nextPageParam | (lastPage, pages, lastPageParam, pageParams) => param: the next page's param, or undefined / null for none. |
previousPageParam | The same, from the first page, for fetchPreviousPage. Default: none, so there's no previous page. |
maxPages | The most pages to keep. Past it, a page is dropped from the far end; give previousPageParam too, so it can load again. Default: no limit. |
schema | { page, pageParam?, error? }: how the pages cross to the browser in server rendering, and how entities find records in them. make and family only. |
It also takes the options in Query options, such
as staleTime and refetchOnFocus, except placeholder and live.
retry applies to each page.
Load more
useInfiniteQuery reads an infinite query, with controls for the next and
previous pages. useSuspenseInfiniteQuery suspends only until the first
page:
import { } from "@monarcode/effetch-query/react";
import { } from "./activity.js";
export function () {
const { , , , } =
(({ : { : "web" } }));
return (
<>
<>
{..
.(() => .)
.(() => (
< ={.}>{.}</>
))}
</>
{ ? (
<
={}
={() => void ()}
>
{ ? "Loading…" : "Load more"}
</>
) : null}
</>
);
}The loaded pages stay on screen while the next one loads.
fetchNextPage never rejects: a page that fails shows in result. In
React Native, call it from FlatList's onEndReached.
Both hooks return result beside the following page controls:
| Control | What it is |
|---|---|
fetchNextPage | Fetches the page after the last one. Resolves when it settles, and never rejects. |
fetchPreviousPage | Fetches the page before the first one, in the same way. |
hasNextPage | Whether nextPageParam gives a param for the shown pages. |
hasPreviousPage | Whether previousPageParam gives a param for the shown pages. |
isFetchingNextPage | Whether a next page is being fetched, as opposed to a refetch of every page. |
isFetchingPreviousPage | Whether a previous page is being fetched. |
While a page loads, result stays a waiting Success, so
isFetchingNextPage is how you tell a page fetch from a background
refetch of every page.
To check fields such as status, data and error instead of matching
on result, use useInfiniteQueryState or
useSuspenseInfiniteQueryState: see
Read pages.
Without Suspense
useInfiniteQuery's result is an AsyncResult, as
useQuery returns, and it fetches when useQuery does.
Pass null to read nothing. It takes useQuery's keepPrevious and
paused options, as Pause screens you can't see
explains. A paused reader's page functions still fetch pages when called.
With Suspense
A page that fails after the first isn't thrown, since there are pages to
show. Only a failure with no pages before it reaches the error boundary,
as a QueryFailure. See
Suspense and error boundaries.
What's next
- Suspense and error boundaries: show the first page's failure in an error boundary.
- Optimistic updates: change loaded pages before the server answers.
- Send the cache: render the first page on the server.