# Query (https://effetch-query.monarcode.dev/docs/reference/query)

`Query` defines queries, and reads and writes the cache from Effect. Import it from the core entry point:

```ts
import { Query } from "@monarcode/effetch-query";
```

Its exports follow, grouped by the guide that covers them, each with its
docs. Your editor shows the same docs, with an example, when you hover the
name.

## Define queries

Guide: [3. Define your queries](https://effetch-query.monarcode.dev/docs/getting-started#3-define-your-queries).

### Query.make

Defines a query with no arguments. Nothing is fetched until it's used.

### Query.family

Defines a [`Family`](https://effetch-query.monarcode.dev/docs/reference/query#family-type): one query per argument, each cached on its own.

Members are weakly held where the runtime has `WeakRef` and `FinalizationRegistry`. Where `typeof FinalizationRegistry` is `"undefined"`, as on React Native with a Hermes older than 260318099.0.0, each distinct argument's query definition stays in memory for the app's lifetime (about 2 KB each, measured on V8). Its cached value is still dropped after `gcTime`, so this matters only for families with many thousands of arguments over a session.

### Query.Family

Makes one [`Query`](https://effetch-query.monarcode.dev/docs/reference/query#query) per argument. Calling it with arguments that are `Equal.equals` (plain objects and arrays compare by structure) returns the same query, whose key is the family's key with the argument appended.

| Prop  | Type  | Description                             |
| ----- | ----- | --------------------------------------- |
| `key` | `Key` | The key every member's key starts with. |

### Query.FamilyOptions

Options for [`family`](https://effetch-query.monarcode.dev/docs/reference/query#family).

| Prop                  | Type       | Description                                                                                                                                                                                                                                                                                                             |
| --------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`                 | `Key`      | The family's key. Each member appends its argument.                                                                                                                                                                                                                                                                     |
| `run`                 | `function` | Fetches one member's value from its argument. It runs with your services and the client, and its `Scope` closes when the fetch settles.                                                                                                                                                                                 |
| `schema?`             | `object`   | How each member's value crosses from server to browser, as MakeOptions.schema.                                                                                                                                                                                                                                          |
| `placeholder?`        | `function` | A value to show for a member until it has one, from the member's argument, as MakeOptions.placeholder. Default: none.                                                                                                                                                                                                   |
| `live?`               | `function` | The server pushes that keep a member's value up to date, from its argument, as MakeOptions.live. Default: none.                                                                                                                                                                                                         |
| `staleTime?`          | `union`    | How long a success counts as fresh. Default: 0, stale at once.                                                                                                                                                                                                                                                          |
| `retry?`              | `object`   | Retries a failed fetch on this schedule, which gets each failure. Defects aren't retried. Default: no retries.                                                                                                                                                                                                          |
| `refetchOnMount?`     | `union`    | If true, refetches a stale query when a component starts using it. Default: `true`.                                                                                                                                                                                                                                     |
| `retryOnMount?`       | `union`    | If true, refetches a failed query when a component starts using it, however recent the failure. A suspense reader (React's `useSuspenseQuery`) of a failure with no earlier value throws it to an error boundary instead, so it never starts using the query to retry it (see `useResetQueryFailure`). Default: `true`. |
| `refetchOnFocus?`     | `union`    | If true, refetches a stale query in use when the app regains focus (CommonOptions.signals). Default: `true`.                                                                                                                                                                                                            |
| `refetchOnReconnect?` | `union`    | If true, refetches a stale query in use when the device reconnects (CommonOptions.signals). Default: `true`.                                                                                                                                                                                                            |
| `refetchInterval?`    | `union`    | The interval at which a query in use refetches. A tick that finds a fetch in progress doesn't start another. Polling pauses while nothing uses the query and resumes when something starts using it. Default: no polling.                                                                                               |
| `gcTime?`             | `union`    | How long a query nothing uses stays cached. Default: 5 minutes. Like `reactivityKeys` and `entities`, it has no client-wide default.                                                                                                                                                                                    |
| `reactivityKeys?`     | `union`    | The `Reactivity` keys that refetch this query when invalidated, for Effect code that publishes them (Effect's SQL clients do). Run `Reactivity.invalidate` through the client, as QueryClient.QueryClient.runPromise does, to reach it. Default: none.                                                                  |
| `entities?`           | `object`   | How this query takes part in the client's entity sync (QueryClient.EntitiesOptions.sync). Default: it does, if it has a `schema`.                                                                                                                                                                                       |

### Query.MakeOptions

Options for [`make`](https://effetch-query.monarcode.dev/docs/reference/query#make).

| Prop                  | Type     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| --------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `key`                 | `Key`    | The query's key.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `run`                 | `union`  | Fetches the value: an Effect, or a function of a RunContext for queries that read other queries. It runs with your services and the client, and its `Scope` closes when the fetch settles.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `schema?`             | `object` | How the value crosses from server to browser; without one, it fetches in the browser.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `placeholder?`        | `object` | A value to show until the query has one, such as an item from a list already cached: an Effect that returns `Option.some(value)`, or `Option.none()` for nothing. It runs with your services and the client, when the query is read with no value, and its value shows as a waiting `Success` until the first fetch settles. If that fetch fails, the failure shows. It's never cached: get, update, fetch and QueryClient.dehydrate don't see it, a query that reads this one through `ctx.result` waits for the fetch, a suspense reader shows it without suspending, and a server render doesn't show it. Run it synchronously, reading the cache with get: an asynchronous one shows once it's done, if the fetch hasn't settled first, though not to a suspense reader already suspended, which waits for the fetch. If it dies, the defect is logged with `Effect.logError` and nothing shows. Default: none.                                                                                                            |
| `live?`               | `object` | The server pushes that keep the value up to date between fetches, such as a WebSocket's messages: a `Stream` of functions, each applied to the value as it arrives. It runs while the query is read, and stops about a second after its last reader leaves; the value stays cached for `gcTime`. fetch doesn't start it. An update that throws is logged with `Effect.logError` and skipped. If the stream fails, the error is logged and it starts again the next time the query is read after its readers leave: add `Stream.retry` to resubscribe sooner. A push keeps the value's age, so `staleTime` and the refetches it drives work as without one. A push that comes while a fetch is in progress is applied to its result too, and one that comes after an optimistic write is applied again if the write is undone, so make each update idempotent: an upsert or a removal by id, not a counter's increment. A push to a query with no value yet (or a failure) is kept only for a fetch in progress. Default: none. |
| `staleTime?`          | `union`  | How long a success counts as fresh. Default: 0, stale at once.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `retry?`              | `object` | Retries a failed fetch on this schedule, which gets each failure. Defects aren't retried. Default: no retries.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `refetchOnMount?`     | `union`  | If true, refetches a stale query when a component starts using it. Default: `true`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `retryOnMount?`       | `union`  | If true, refetches a failed query when a component starts using it, however recent the failure. A suspense reader (React's `useSuspenseQuery`) of a failure with no earlier value throws it to an error boundary instead, so it never starts using the query to retry it (see `useResetQueryFailure`). Default: `true`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `refetchOnFocus?`     | `union`  | If true, refetches a stale query in use when the app regains focus (CommonOptions.signals). Default: `true`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `refetchOnReconnect?` | `union`  | If true, refetches a stale query in use when the device reconnects (CommonOptions.signals). Default: `true`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `refetchInterval?`    | `union`  | The interval at which a query in use refetches. A tick that finds a fetch in progress doesn't start another. Polling pauses while nothing uses the query and resumes when something starts using it. Default: no polling.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `gcTime?`             | `union`  | How long a query nothing uses stays cached. Default: 5 minutes. Like `reactivityKeys` and `entities`, it has no client-wide default.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `reactivityKeys?`     | `union`  | The `Reactivity` keys that refetch this query when invalidated, for Effect code that publishes them (Effect's SQL clients do). Run `Reactivity.invalidate` through the client, as QueryClient.QueryClient.runPromise does, to reach it. Default: none.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `entities?`           | `object` | How this query takes part in the client's entity sync (QueryClient.EntitiesOptions.sync). Default: it does, if it has a `schema`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |

## Queries

Guide: [Queries from any Effect](https://effetch-query.monarcode.dev/docs/queries/without-effetch).

### Query.Query

A cached query: an atom whose value is the query's `AsyncResult`, with a key. Create one with [`make`](https://effetch-query.monarcode.dev/docs/reference/query#make), or one per argument with [`family`](https://effetch-query.monarcode.dev/docs/reference/query#family).

Because it's an atom, it works with `@effect/atom-react`'s hooks, `Atom.map` and the rest of `effect/reactivity`. Writing to it shows the written value until a fetch that settles after the write. Prefer [`set`](https://effetch-query.monarcode.dev/docs/reference/query#set): on a query that isn't cached, a plain atom write (such as `registry.set` or `useAtomSet`) is kept but the query still fetches when it's first read, while [`set`](https://effetch-query.monarcode.dev/docs/reference/query#set) caches the value without fetching.

### Query.isQuery

Checks whether a value is a [`Query`](https://effetch-query.monarcode.dev/docs/reference/query#query), as opposed to another atom or value.

### Query.TypeId

The property that marks a [`Query`](https://effetch-query.monarcode.dev/docs/reference/query#query), so it can be told apart from other atoms.

## Query options

Guide: [Query options](https://effetch-query.monarcode.dev/docs/queries/options).

### Query.Options

The options every query takes besides `key` and `run`, in [`MakeOptions`](https://effetch-query.monarcode.dev/docs/reference/query#makeoptions) and [`FamilyOptions`](https://effetch-query.monarcode.dev/docs/reference/query#familyoptions). Each one a query sets overrides the client's `queries.defaults` ([`QueryClient.QueryDefaults`](https://effetch-query.monarcode.dev/docs/reference/query-client#querydefaults)).

| Prop                  | Type     | Description                                                                                                                                                                                                                                                                                                             |
| --------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `gcTime?`             | `union`  | How long a query nothing uses stays cached. Default: 5 minutes. Like `reactivityKeys` and `entities`, it has no client-wide default.                                                                                                                                                                                    |
| `reactivityKeys?`     | `union`  | The `Reactivity` keys that refetch this query when invalidated, for Effect code that publishes them (Effect's SQL clients do). Run `Reactivity.invalidate` through the client, as QueryClient.QueryClient.runPromise does, to reach it. Default: none.                                                                  |
| `entities?`           | `object` | How this query takes part in the client's entity sync (QueryClient.EntitiesOptions.sync). Default: it does, if it has a `schema`.                                                                                                                                                                                       |
| `staleTime?`          | `union`  | How long a success counts as fresh. Default: 0, stale at once.                                                                                                                                                                                                                                                          |
| `retry?`              | `object` | Retries a failed fetch on this schedule, which gets each failure. Defects aren't retried. Default: no retries.                                                                                                                                                                                                          |
| `refetchOnMount?`     | `union`  | If true, refetches a stale query when a component starts using it. Default: `true`.                                                                                                                                                                                                                                     |
| `retryOnMount?`       | `union`  | If true, refetches a failed query when a component starts using it, however recent the failure. A suspense reader (React's `useSuspenseQuery`) of a failure with no earlier value throws it to an error boundary instead, so it never starts using the query to retry it (see `useResetQueryFailure`). Default: `true`. |
| `refetchOnFocus?`     | `union`  | If true, refetches a stale query in use when the app regains focus (CommonOptions.signals). Default: `true`.                                                                                                                                                                                                            |
| `refetchOnReconnect?` | `union`  | If true, refetches a stale query in use when the device reconnects (CommonOptions.signals). Default: `true`.                                                                                                                                                                                                            |
| `refetchInterval?`    | `union`  | The interval at which a query in use refetches. A tick that finds a fetch in progress doesn't start another. Polling pauses while nothing uses the query and resumes when something starts using it. Default: no polling.                                                                                               |

## Keep copies in sync

Guide: [Keep copies in sync](https://effetch-query.monarcode.dev/docs/cache/entity-sync).

### Query.EntitiesOptions

A query's `entities` option ([`Options`](https://effetch-query.monarcode.dev/docs/reference/query#options)): whether the client's entity sync (`QueryClient.EntitiesOptions.sync`) reads this query's copies and writes over them.

| Prop    | Type    | Description                                                                                                                                                                                                                                                            |
| ------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sync?` | `union` | If false, entity sync leaves this query out both ways: a fetch of it updates no other query, and no other query's fetch updates it. For a deliberately partial view whose copies shouldn't overwrite fuller ones. `Entity` writes reach it as before. Default: `true`. |

## Query keys

Guide: [Query keys](https://effetch-query.monarcode.dev/docs/queries/keys).

### Query.Key

Identifies a query in the cache. Keys are hierarchical arrays: each segment is compared with `Equal.equals`, so plain objects and arrays match by structure, and a key matches every longer key it is a prefix of (see [`Target`](https://effetch-query.monarcode.dev/docs/reference/query#target)).

Keep keys JSON-compatible (strings, numbers, booleans, `null`, and arrays and plain objects of them): with server rendering, they're sent to the browser to find each query again.

## Queries that read other queries

Guide: [Queries that read other queries](https://effetch-query.monarcode.dev/docs/queries/dependent).

### Query.RunContext

What a query's `run` receives, for reading other queries: given to [`make`](https://effetch-query.monarcode.dev/docs/reference/query#make)'s `run` and as the second argument of [`family`](https://effetch-query.monarcode.dev/docs/reference/query#family)'s.

| Prop     | Type       | Description                                                                                                                                                                                                                                                                   |
| -------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `result` | `function` | Reads another query's value and makes this query depend on it: this query refetches when that query's value or failure changes, as when a refetch of it settles or it's written, but not while a refetch of it runs. Waits while it has no value yet, and fails if it failed. |

## Send the cache

Guide: [Send the cache](https://effetch-query.monarcode.dev/docs/server-rendering).

### Query.Schema

How a query's value is sent from the server to the browser, for server rendering: Schemas for its value and, to send failures too, its error. Only queries with one are sent ([`QueryClient.dehydrate`](https://effetch-query.monarcode.dev/docs/reference/query-client#dehydrate)); the rest fetch in the browser. Pass the schemas themselves: the JSON codec is derived from each (`Schema.toCodecJson`), so each must encode to JSON and need no services.

| Prop      | Type     | Description                                       |
| --------- | -------- | ------------------------------------------------- |
| `success` | `object` | The value's schema.                               |
| `error?`  | `object` | The error's schema, needed only to send failures. |

## Queries from a stream

Guide: [Queries from a stream](https://effetch-query.monarcode.dev/docs/queries/streams).

### Query.stream

Defines a query whose value is the latest element of a `Stream`, such as prices from a WebSocket or events from Server-Sent Events. Nothing runs until it's used.

- The stream runs while the query is read, and stops about a second after its last reader leaves; the value stays cached for `gcTime`, and the stream starts again for the next reader.
- Until the first element, the query is `Initial` and waiting, so a suspense reader suspends and [`fetch`](https://effetch-query.monarcode.dev/docs/reference/query#fetch) waits; after it, each element shows as a `Success` stamped with the time it came.
- [`refetch`](https://effetch-query.monarcode.dev/docs/reference/query#refetch), [`invalidate`](https://effetch-query.monarcode.dev/docs/reference/query#invalidate) and [`reset`](https://effetch-query.monarcode.dev/docs/reference/query#reset) subscribe again; [`clear`](https://effetch-query.monarcode.dev/docs/reference/query#clear) stops the stream until something asks for the query again.
- If the stream fails, it's resubscribed on `retry`; once that's done, the query shows the failure with the last element as its previous success. A stream that ends keeps its last element; one that ends with none fails with a `NoSuchElementError` defect.
- A server render shows only what's cached, and doesn't start it. [`prefetch`](https://effetch-query.monarcode.dev/docs/reference/query#prefetch) on the server runs it to its first element, which [`QueryClient.dehydrate`](https://effetch-query.monarcode.dev/docs/reference/query-client#dehydrate) sends with a `schema`.

### Query.streamFamily

Defines a [`Family`](https://effetch-query.monarcode.dev/docs/reference/query#family-type) of stream queries: one per argument, each with its own stream, as [`stream`](https://effetch-query.monarcode.dev/docs/reference/query#stream) makes one.

### Query.MakeStreamOptions

Options for [`stream`](https://effetch-query.monarcode.dev/docs/reference/query#stream).

| Prop              | Type     | Description                                                                                                                                                                                                                 |
| ----------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`             | `Key`    | The query's key.                                                                                                                                                                                                            |
| `run`             | `union`  | The stream whose elements are the value: a `Stream`, or a function of a RunContext for streams that read other queries. It runs with your services and the client.                                                          |
| `schema?`         | `object` | The schemas that send the latest value from server to browser, as MakeOptions.schema.                                                                                                                                       |
| `placeholder?`    | `object` | A value to show until the first element, as MakeOptions.placeholder. Default: none.                                                                                                                                         |
| `gcTime?`         | `union`  | The time a query nothing uses stays cached, as Options.gcTime. Default: 5 minutes.                                                                                                                                          |
| `retry?`          | `object` | The schedule to resubscribe on after the stream fails, as `Stream.retry` takes it: the schedule starts over once an element comes through. Defects aren't retried. Default: the client's `queries.defaults.retry`, or none. |
| `retryOnMount?`   | `union`  | If true, a query whose stream failed subscribes again when something starts using it. Default: the client's `queries.defaults.retryOnMount`, or `true`.                                                                     |
| `reactivityKeys?` | `union`  | The `Reactivity` keys that resubscribe this query when invalidated, as Options.reactivityKeys. Default: none.                                                                                                               |

### Query.StreamFamilyOptions

Options for [`streamFamily`](https://effetch-query.monarcode.dev/docs/reference/query#streamfamily).

| Prop              | Type       | Description                                                                                                                                                                                                                 |
| ----------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`             | `Key`      | The family's key. Each member appends its argument.                                                                                                                                                                         |
| `run`             | `function` | The stream whose elements are one member's value, from its argument.                                                                                                                                                        |
| `schema?`         | `object`   | The schemas that send each member's latest value from server to browser, as MakeOptions.schema.                                                                                                                             |
| `placeholder?`    | `function` | A value to show for a member until its first element, as FamilyOptions.placeholder. Default: none.                                                                                                                          |
| `gcTime?`         | `union`    | The time a query nothing uses stays cached, as Options.gcTime. Default: 5 minutes.                                                                                                                                          |
| `retry?`          | `object`   | The schedule to resubscribe on after the stream fails, as `Stream.retry` takes it: the schedule starts over once an element comes through. Defects aren't retried. Default: the client's `queries.defaults.retry`, or none. |
| `retryOnMount?`   | `union`    | If true, a query whose stream failed subscribes again when something starts using it. Default: the client's `queries.defaults.retryOnMount`, or `true`.                                                                     |
| `reactivityKeys?` | `union`    | The `Reactivity` keys that resubscribe this query when invalidated, as Options.reactivityKeys. Default: none.                                                                                                               |

### Query.StreamOptions

The options every stream query takes besides `key` and `run`, in [`MakeStreamOptions`](https://effetch-query.monarcode.dev/docs/reference/query#makestreamoptions) and [`StreamFamilyOptions`](https://effetch-query.monarcode.dev/docs/reference/query#streamfamilyoptions). A stream keeps its query current, so it has no `staleTime`, and nothing refetches it on focus, reconnect or an interval, nor when something starts using it, except a failed one with `retryOnMount`.

| Prop              | Type     | Description                                                                                                                                                                                                                 |
| ----------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `gcTime?`         | `union`  | The time a query nothing uses stays cached, as Options.gcTime. Default: 5 minutes.                                                                                                                                          |
| `retry?`          | `object` | The schedule to resubscribe on after the stream fails, as `Stream.retry` takes it: the schedule starts over once an element comes through. Defects aren't retried. Default: the client's `queries.defaults.retry`, or none. |
| `retryOnMount?`   | `union`  | If true, a query whose stream failed subscribes again when something starts using it. Default: the client's `queries.defaults.retryOnMount`, or `true`.                                                                     |
| `reactivityKeys?` | `union`  | The `Reactivity` keys that resubscribe this query when invalidated, as Options.reactivityKeys. Default: none.                                                                                                               |

## Use the cache from Effect

Guide: [Read and write the cache](https://effetch-query.monarcode.dev/docs/cache).

### Query.clear

Drops the matching queries' values, and those written with [`set`](https://effetch-query.monarcode.dev/docs/reference/query#set), without fetching: TanStack's `removeQueries` and `queryClient.clear()`. Use it when the values must go and refetching would fail, such as on signing out.

- A query in use shows `Initial`, not waiting, and a fetch in progress is interrupted. It stays empty through focus, reconnect, `refetchInterval` and `Reactivity` keys, until something asks for it: a component that starts using it, [`fetch`](https://effetch-query.monarcode.dev/docs/reference/query#fetch), [`invalidate`](https://effetch-query.monarcode.dev/docs/reference/query#invalidate) or [`refetch`](https://effetch-query.monarcode.dev/docs/reference/query#refetch).
- A component already showing it keeps showing `Initial`; one using `useSuspenseQuery` shows its Suspense fallback.
- A query not in use fetches the next time it's used, as after [`reset`](https://effetch-query.monarcode.dev/docs/reference/query#reset). So does one no one has read since `QueryClient.hydrate` gave it the server's value.
- A query whose `run` reads a cleared one through `ctx.result` is cleared too, since its value came from it. When it's asked for again, it asks for what it reads.
- A [`fetch`](https://effetch-query.monarcode.dev/docs/reference/query#fetch) waiting on it is interrupted, and a [`refetch`](https://effetch-query.monarcode.dev/docs/reference/query#refetch) waiting on it completes: neither starts a fetch.
- A mutation's optimistic write made before it isn't rolled back over it: the cleared values don't come back. One made after it is rolled back to the cleared state.
- With `keepPrevious`, a component doesn't show a cleared value as its previous one.

A component reading a derived atom through `useAtomValue` doesn't ask for the query, so it stays empty until something else does.

### Query.fetch

Returns a query's value: the cached one if it's fresh (younger than `staleTime`), otherwise the result of a new fetch. Joins a fetch already in progress. Fails with the query's error, and dies on defects, as its own Effect does. To read the cache without fetching, use [`get`](https://effetch-query.monarcode.dev/docs/reference/query#get).

### Query.get

Returns a query's cached value, if it has one. Never fetches (use [`fetch`](https://effetch-query.monarcode.dev/docs/reference/query#fetch) for that). A query whose last fetch failed still returns the value it had before. Write it with [`set`](https://effetch-query.monarcode.dev/docs/reference/query#set) or [`update`](https://effetch-query.monarcode.dev/docs/reference/query#update). Outside Effect, read it with [`QueryClient.get`](https://effetch-query.monarcode.dev/docs/reference/query-client#get).

### Query.invalidate

Marks the matching queries stale. Those in use (as [`refetch`](https://effetch-query.monarcode.dev/docs/reference/query#refetch) defines it) refetch at once; the others refetch the next time they're used. Completes without waiting for the refetches.

### Query.prefetch

Fetches a query unless its value is fresh, like [`fetch`](https://effetch-query.monarcode.dev/docs/reference/query#fetch), but never fails: use it to warm the cache before the value is needed. Completes when the fetch settles; a failure shows in the query's result instead.

### Query.refetch

Refetches the matching queries that are in use, and completes when they have all settled. Their failures don't fail it: each query shows its own.

A query is in use while something subscribes to it, or to an atom or query that depends on it: a mounted component, say, or a mounted query that reads it through `RunContext.result`. A dependent that is only cached doesn't count.

### Query.reset

Puts the matching queries back to `Initial`, dropping their values and any written with [`set`](https://effetch-query.monarcode.dev/docs/reference/query#set). Those in use (as [`refetch`](https://effetch-query.monarcode.dev/docs/reference/query#refetch) defines it) fetch again at once, and a fetch in progress is replaced; the others fetch the next time they're used. Completes without waiting for the fetches.

### Query.set

Writes a query's value. It's shown until a fetch settles after the write, including while that fetch is in progress; if the fetch fails, it stays as the query's last value. A query that isn't cached yet is cached with the value, without fetching. The value counts as fresh data: a query invalidated while nothing used it isn't refetched for it until it's older than `staleTime`. The client's `queries` hooks don't run for it. Made in a mutation's `optimistic`, the write is undone if the run fails.

### Query.update

Writes a value computed from a query's cached one, as [`set`](https://effetch-query.monarcode.dev/docs/reference/query#set) does, and is undone the same way in a mutation's `optimistic`. Does nothing if the query has no value.

Given a [`Family`](https://effetch-query.monarcode.dev/docs/reference/query#family-type), it writes every cached member, as TanStack's `setQueriesData` does: `f` gets each member's value and its argument. Members are the family's own queries, not every query under its key, and only those with a value are written: none is created. In a mutation's `optimistic`, a failed run puts each member back.

## Targets

Guide: [Targets](https://effetch-query.monarcode.dev/docs/queries/keys#targets).

### Query.group

Combines targets into one [`Group`](https://effetch-query.monarcode.dev/docs/reference/query#group-type), for acting on unrelated queries together: pass it wherever a [`Target`](https://effetch-query.monarcode.dev/docs/reference/query#target) goes, to [`refetch`](https://effetch-query.monarcode.dev/docs/reference/query#refetch), [`invalidate`](https://effetch-query.monarcode.dev/docs/reference/query#invalidate), [`reset`](https://effetch-query.monarcode.dev/docs/reference/query#reset), [`clear`](https://effetch-query.monarcode.dev/docs/reference/query#clear), a mutation's `invalidates` or `useRefetch`. It matches every query one of its targets matches, and each only once, so a family and one of its own queries in a group refetch that query once. Groups given to it are flattened.

Writes don't take a group, since a value can't fit queries of different types: [`set`](https://effetch-query.monarcode.dev/docs/reference/query#set) and [`update`](https://effetch-query.monarcode.dev/docs/reference/query#update) take one query or family.

Pass the targets as separate arguments, not an array: `[wallet, transactions]` is a [`Key`](https://effetch-query.monarcode.dev/docs/reference/query#key), which would match nothing, so [`GroupTargets`](https://effetch-query.monarcode.dev/docs/reference/query#grouptargets) makes it a type error.

### Query.KeyHoldsTargetError

Thrown when a key holds a query, a family or a group, such as `Query.invalidate([wallet, transactions])`. Its segments are compared with the query keys, so as a key it would match nothing: the targets were meant to be one target. Combine them with [`Query.group`](https://effetch-query.monarcode.dev/docs/reference/query#group).

Everything that takes a [`Query.Target`](https://effetch-query.monarcode.dev/docs/reference/query#target) checks it, and reports it in its own way:

- the `Query` functions, such as `Query.invalidate`, die with it, and so does `Mutation.run` for a key in `invalidates`;
- the client's methods, such as `client.refetch`, reject with it;
- `useRefetch`, `useIsFetching` and `QueryClient.dehydrate`'s `queries` throw it when called;
- `connectQueryClient`'s `queries` fails each server render, when the router dehydrates the client.

### Query.Group

Several targets as one, made by [`group`](https://effetch-query.monarcode.dev/docs/reference/query#group): it matches every query one of its targets matches, each once. Use it to act on unrelated queries together, such as a screen's pull to refresh.

| Prop                              | Type                                | Description                                                     |
| --------------------------------- | ----------------------------------- | --------------------------------------------------------------- |
| `~@monarcode/effetch-query/Group` | `"~@monarcode/effetch-query/Group"` | Marks a group.                                                  |
| `targets`                         | `array`                             | Its targets, with any group given to group replaced by its own. |

### Query.GroupTargets

The targets [`group`](https://effetch-query.monarcode.dev/docs/reference/query#group) takes: any [`Target`](https://effetch-query.monarcode.dev/docs/reference/query#target), except an array that holds a query, a family or a group. Such an array is a [`Key`](https://effetch-query.monarcode.dev/docs/reference/query#key), whose segments are compared with the query keys, so it would match nothing: the targets were meant to be passed one by one.

### Query.Target

What [`invalidate`](https://effetch-query.monarcode.dev/docs/reference/query#invalidate), [`refetch`](https://effetch-query.monarcode.dev/docs/reference/query#refetch), [`reset`](https://effetch-query.monarcode.dev/docs/reference/query#reset) and [`clear`](https://effetch-query.monarcode.dev/docs/reference/query#clear) act on: a [`Query`](https://effetch-query.monarcode.dev/docs/reference/query#query) (that key only), a [`Family`](https://effetch-query.monarcode.dev/docs/reference/query#family-type) (every query whose key starts with the family's, its members included; an Effetch endpoint matches only its own queries), a [`Key`](https://effetch-query.monarcode.dev/docs/reference/query#key) (every query whose key starts with it, so `[]` matches every query), or a [`Group`](https://effetch-query.monarcode.dev/docs/reference/query#group-type) of these (every query one of them matches).

An array of queries is a key, not a group, and as a key it would match nothing: `[wallet, transactions]` fails with a [`KeyHoldsTargetError`](https://effetch-query.monarcode.dev/docs/reference/query#keyholdstargeterror) defect instead. Combine targets with [`group`](https://effetch-query.monarcode.dev/docs/reference/query#group).