Query
Every member of the Query namespace: defining queries, keys and targets, streams, and reading and writing the cache from Effect.
Query defines queries, and reads and writes the cache from Effect. Import it from the core entry point:
import { } 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.
Query.make
Defines a query with no arguments. Nothing is fetched until it's used.
Query.family
Defines a Family: 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 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
Query.FamilyOptions
Options for family.
Prop
Type
Query.MakeOptions
Options for make.
Prop
Type
Queries
Guide: Queries from any Effect.
Query.Query
A cached query: an atom whose value is the query's AsyncResult, with a key. Create one with make, or one per argument with 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: 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 caches the value without fetching.
Query.isQuery
Checks whether a value is a Query, as opposed to another atom or value.
Query.TypeId
The property that marks a Query, so it can be told apart from other atoms.
Query options
Guide: Query options.
Query.Options
The options every query takes besides key and run, in MakeOptions and FamilyOptions. Each one a query sets overrides the client's queries.defaults (QueryClient.QueryDefaults).
Prop
Type
Keep copies in sync
Guide: Keep copies in sync.
Query.EntitiesOptions
A query's entities option (Options): whether the client's entity sync (QueryClient.EntitiesOptions.sync) reads this query's copies and writes over them.
Prop
Type
Query keys
Guide: Query 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).
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.
Query.RunContext
What a query's run receives, for reading other queries: given to make's run and as the second argument of family's.
Prop
Type
Send the cache
Guide: Send the cache.
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); 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
Queries from a stream
Guide: Queries from a stream.
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
Initialand waiting, so a suspense reader suspends andfetchwaits; after it, each element shows as aSuccessstamped with the time it came. refetch,invalidateandresetsubscribe again;clearstops 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 aNoSuchElementErrordefect. - A server render shows only what's cached, and doesn't start it.
prefetchon the server runs it to its first element, whichQueryClient.dehydratesends with aschema.
Query.streamFamily
Defines a Family of stream queries: one per argument, each with its own stream, as stream makes one.
Query.MakeStreamOptions
Options for stream.
Prop
Type
Query.StreamFamilyOptions
Options for streamFamily.
Prop
Type
Query.StreamOptions
The options every stream query takes besides key and run, in MakeStreamOptions and 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
Use the cache from Effect
Guide: Read and write the cache.
Query.clear
Drops the matching queries' values, and those written with 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,refetchIntervalandReactivitykeys, until something asks for it: a component that starts using it,fetch,invalidateorrefetch. - A component already showing it keeps showing
Initial; one usinguseSuspenseQueryshows its Suspense fallback. - A query not in use fetches the next time it's used, as after
reset. So does one no one has read sinceQueryClient.hydrategave it the server's value. - A query whose
runreads a cleared one throughctx.resultis cleared too, since its value came from it. When it's asked for again, it asks for what it reads. - A
fetchwaiting on it is interrupted, and arefetchwaiting 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.
Query.get
Returns a query's cached value, if it has one. Never fetches (use fetch for that). A query whose last fetch failed still returns the value it had before. Write it with set or update. Outside Effect, read it with QueryClient.get.
Query.invalidate
Marks the matching queries stale. Those in use (as 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, 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. Those in use (as 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 does, and is undone the same way in a mutation's optimistic. Does nothing if the query has no value.
Given a Family, 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.
Query.group
Combines targets into one Group, for acting on unrelated queries together: pass it wherever a Target goes, to refetch, invalidate, reset, 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 and update take one query or family.
Pass the targets as separate arguments, not an array: [wallet, transactions] is a Key, which would match nothing, so 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.
Everything that takes a Query.Target checks it, and reports it in its own way:
- the
Queryfunctions, such asQuery.invalidate, die with it, and so doesMutation.runfor a key ininvalidates; - the client's methods, such as
client.refetch, reject with it; useRefetch,useIsFetchingandQueryClient.dehydrate'squeriesthrow it when called;connectQueryClient'squeriesfails each server render, when the router dehydrates the client.
Query.Group
Several targets as one, made by 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
Query.GroupTargets
The targets group takes: any Target, except an array that holds a query, a family or a group. Such an array is a 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, refetch, reset and clear act on: a Query (that key only), a Family (every query whose key starts with the family's, its members included; an Effetch endpoint matches only its own queries), a Key (every query whose key starts with it, so [] matches every query), or a Group 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 defect instead. Combine targets with group.