# Infinite queries (https://effetch-query.monarcode.dev/docs/queries/infinite)

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](https://effetch-query.monarcode.dev/docs/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:

```ts activity.ts
import * as Schema from "effect/Schema";

import { Fetch } from "@monarcode/effetch";

import { api } from "./todos.js";

const ActivityPage = Schema.Struct({
  events: Schema.Array(
    Schema.Struct({ id: Schema.String, text: Schema.String }),
  ),
  nextCursor: Schema.NullOr(Schema.String),
});

export const activity = api.infiniteQuery(
  Fetch.endpoint("GET /activity", { output: ActivityPage }),
  {
    // Sent as ?cursor=…, and left out of the key.
    pageParam: "cursor",
    initialPageParam: null as string | null,
    // null or undefined: there's no next page.
    nextPageParam: (lastPage) => lastPage.nextCursor,
  },
);
// 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 `query` schema, `pageParam` names 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:

```ts
import * as Schema from "effect/Schema";

import { InfiniteQuery } from "@monarcode/effetch-query";

import { ApiClient, Todo } from "./api.js";

const TodosPage = Schema.Struct({
  todos: Schema.Array(Todo),
  skip: Schema.Finite,
  limit: Schema.Finite,
  total: Schema.Finite,
});

export const todoPages = InfiniteQuery.family({
  key: ["todos", "pages"],
  initialPageParam: 0,
  // The member's argument, then the page's param.
  run: (limit: number, skip) =>
    ApiClient.use((client) =>
      client.get("/todos", { query: { limit, skip }, output: TodosPage }),
    ),
  nextPageParam: (last) =>
    last.skip + last.limit < last.total ? last.skip + last.limit : undefined,
  // Lets the list load pages before the first, and reload dropped ones.
  previousPageParam: (first) =>
    first.skip > 0 ? Math.max(0, first.skip - first.limit) : undefined,
  maxPages: 10,
  // How each page crosses to the browser, and how entities find records in it.
  schema: { page: TodosPage },
});
// 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`](https://effetch-query.monarcode.dev/docs/queries/infinite#load-more), or as
`InfiniteQuery.fetchNextPage` in Effect code:

- When there's no next page, `fetchNextPage` returns the loaded pages
  without fetching. `fetchPreviousPage` does the same, and without
  `previousPageParam` there'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 `Failure`
  whose `previousSuccess` still 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 `fetchNextPage` joins 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:

```ts
import * as Effect from "effect/Effect";

import { InfiniteQuery } from "@monarcode/effetch-query";

import { activity } from "./activity.js";

export const loadMore = Effect.map(
  InfiniteQuery.fetchNextPage(activity({ query: { team: "web" } })),
  (data) => data.pages.flatMap((page) => page.events),
);
```

An infinite query is a query: invalidation,
[the cache functions](https://effetch-query.monarcode.dev/docs/cache) and the client's defaults work on it
as on any other. To change its pages in an
[optimistic update](https://effetch-query.monarcode.dev/docs/mutations/optimistic), `Query.update` the whole
`{ pages, pageParams }` value; on a family, `Query.update` writes every
cached member. [Entities](https://effetch-query.monarcode.dev/docs/cache/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](https://effetch-query.monarcode.dev/docs/queries/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:

```tsx
import { useSuspenseInfiniteQuery } from "@monarcode/effetch-query/react";

import { activity } from "./activity.js";

export function ActivityFeed() {
  const { result, fetchNextPage, hasNextPage, isFetchingNextPage } =
    useSuspenseInfiniteQuery(activity({ query: { team: "web" } }));

  return (
    <>
      <ul>
        {result.value.pages
          .flatMap((page) => page.events)
          .map((event) => (
            <li key={event.id}>{event.text}</li>
          ))}
      </ul>
      {hasNextPage ? (
        <button
          disabled={isFetchingNextPage}
          onClick={() => void fetchNextPage()}
        >
          {isFetchingNextPage ? "Loading…" : "Load more"}
        </button>
      ) : 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](https://effetch-query.monarcode.dev/docs/react/as-object#read-pages).

### Without Suspense

`useInfiniteQuery`'s `result` is an `AsyncResult`, as
[`useQuery`](https://effetch-query.monarcode.dev/docs/react) 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](https://effetch-query.monarcode.dev/docs/react/pause)
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](https://effetch-query.monarcode.dev/docs/react/suspense).

## What's next

- [Suspense and error boundaries](https://effetch-query.monarcode.dev/docs/react/suspense): show the first
  page's failure in an error boundary.
- [Optimistic updates](https://effetch-query.monarcode.dev/docs/mutations/optimistic): change loaded pages
  before the server answers.
- [Send the cache](https://effetch-query.monarcode.dev/docs/server-rendering): render the first page on the
  server.