@raf-query/core 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,19 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.1.2](https://github.com/KATT/raf-query/compare/0.1.1...0.1.2) (2026-10-12)
4
+
5
+ ### Features
6
+
7
+ * add isFetching(filter?) and useIsFetching(filter?) ([#25](https://github.com/KATT/raf-query/issues/25)) ([70c3b98](https://github.com/KATT/raf-query/commit/70c3b981027f717b1d619d5a2b23822f685c032a))
8
+
9
+ ## [0.1.1](https://github.com/KATT/raf-query/compare/0.1.0...0.1.1) (2026-10-12)
10
+
11
+ ### Features
12
+
13
+ - **core:** add predicate to QueryFilter ([#24](https://github.com/KATT/raf-query/issues/24)) ([c0b9c18](https://github.com/KATT/raf-query/commit/c0b9c1829cb3b6446f765b151e520f0195af5276))
14
+
3
15
  ## [0.1.0](https://github.com/KATT/raf-query/compare/0.0.19...0.1.0) (2026-10-12)
4
16
 
5
17
  ### ⚠ BREAKING CHANGES
6
18
 
7
- * Effect-native engine; core exposes only Effect APIs ([#23](https://github.com/KATT/raf-query/issues/23))
8
- * **core:** make QueryObserver an Effect-style data type ([#29](https://github.com/KATT/raf-query/issues/29))
19
+ - Effect-native engine; core exposes only Effect APIs ([#23](https://github.com/KATT/raf-query/issues/23))
20
+ - **core:** make QueryObserver an Effect-style data type ([#29](https://github.com/KATT/raf-query/issues/29))
9
21
 
10
- * **core:** make QueryObserver an Effect-style data type ([#29](https://github.com/KATT/raf-query/issues/29)) ([50fbb45](https://github.com/KATT/raf-query/commit/50fbb45bf3edcaa83673e2177894a76bdf76560b))
11
- * Effect-native engine; core exposes only Effect APIs ([#23](https://github.com/KATT/raf-query/issues/23)) ([8e0bb09](https://github.com/KATT/raf-query/commit/8e0bb09a63d644ede053f443406a521ff2613a6f))
22
+ - **core:** make QueryObserver an Effect-style data type ([#29](https://github.com/KATT/raf-query/issues/29)) ([50fbb45](https://github.com/KATT/raf-query/commit/50fbb45bf3edcaa83673e2177894a76bdf76560b))
23
+ - Effect-native engine; core exposes only Effect APIs ([#23](https://github.com/KATT/raf-query/issues/23)) ([8e0bb09](https://github.com/KATT/raf-query/commit/8e0bb09a63d644ede053f443406a521ff2613a6f))
12
24
 
13
25
  ### Features
14
26
 
15
- * **core:** stream SSR dehydration as Effect APIs; integrations become thin edges ([#30](https://github.com/KATT/raf-query/issues/30)) ([6b2b570](https://github.com/KATT/raf-query/commit/6b2b5703f5463c0f3805c233cf4ead90df9efb76)), references [#29](https://github.com/KATT/raf-query/issues/29)
16
- * typed services for Effect queries; QueryClient layer and dispose() ([#31](https://github.com/KATT/raf-query/issues/31)) ([6aeaa3d](https://github.com/KATT/raf-query/commit/6aeaa3d356f6483654729620ac26762508eb8fd8))
27
+ - **core:** stream SSR dehydration as Effect APIs; integrations become thin edges ([#30](https://github.com/KATT/raf-query/issues/30)) ([6b2b570](https://github.com/KATT/raf-query/commit/6b2b5703f5463c0f3805c233cf4ead90df9efb76)), references [#29](https://github.com/KATT/raf-query/issues/29)
28
+ - typed services for Effect queries; QueryClient layer and dispose() ([#31](https://github.com/KATT/raf-query/issues/31)) ([6aeaa3d](https://github.com/KATT/raf-query/commit/6aeaa3d356f6483654729620ac26762508eb8fd8))
17
29
 
18
30
  ## [0.0.19](https://github.com/KATT/raf-query/compare/0.0.18...0.0.19) (2026-10-12)
19
31
 
package/README.md CHANGED
@@ -196,6 +196,16 @@ When the cache updates — refetch, invalidation, `setData` — the hook returns
196
196
 
197
197
  Queries do not refetch on mount. They refetch when a loader starts them again, when invalidated, on window focus or reconnect while stale, on `refetch()`, or on `refetchInterval`.
198
198
 
199
+ For an app-wide indicator, `useIsFetching()` returns how many queries have a request in flight, background refetches included, and re-renders when that changes. Pass a filter to count only some: `useIsFetching({ queryKey: ["comments"] })`. It's `0` on the server and during hydration, so the indicator never appears in server HTML. Outside React, `qc.isFetching(filter?)` returns the same number.
200
+
201
+ ```tsx
202
+ // Rendered once, in the root layout.
203
+ function GlobalProgress() {
204
+ const fetching = useIsFetching();
205
+ return fetching > 0 ? <ProgressBar /> : null;
206
+ }
207
+ ```
208
+
199
209
  ### Paged queries
200
210
 
201
211
  With an `infiniteQueryOptions` factory, `useQuery` returns the same tuple. The promise resolves to `{ pages, pageParams }`, and the controls add paging:
@@ -358,12 +368,22 @@ function EditTitle(props: { post: Post }) {
358
368
 
359
369
  `updatePost` is a server function (or a Next.js server action). `await qc.invalidate(...)` resolves once every query currently being read has refetched, so the action's pending state lasts until the fresh data is on screen. For an error message, wrap the action in `useActionState` and return the caught error.
360
370
 
361
- | Call | Effect |
362
- | ------------------------------------- | ----------------------------------------------------------------------- |
363
- | `qc.invalidate(factory, input)` | Mark one query stale and refetch it if it is being read |
364
- | `qc.invalidate({ queryKey, exact? })` | Same, for every query whose key starts with `queryKey` (unless `exact`) |
365
- | `qc.setData(factory, input, updater)` | Write data directly |
366
- | `qc.getData(factory, input)` | Read cached data, or `undefined` |
371
+ | Call | Effect |
372
+ | ------------------------------------- | ------------------------------------------------------- |
373
+ | `qc.invalidate(factory, input)` | Mark one query stale and refetch it if it is being read |
374
+ | `qc.invalidate(filter)` | Same, for every query the [filter](#filters) selects |
375
+ | `qc.setData(factory, input, updater)` | Write data directly |
376
+ | `qc.getData(factory, input)` | Read cached data, or `undefined` |
377
+
378
+ ### Filters
379
+
380
+ `invalidate`, `reset` and `remove` also take a filter, `{ queryKey?, exact?, predicate? }`. `queryKey` selects every query whose key starts with it, or only that key with `exact: true`; object segments match partially, so `{ queryKey: ["issues", { projectId: 3 }] }` selects every issue list in project 3. `predicate` gets each remaining `Query` and keeps the ones it returns `true` for: read its `key` and `handle.input`, or use the `Query` functions (`Query.getUnsafe(query)` for its state, `Query.observerCountUnsafe(query)`, `Query.isStaleUnsafe(query)`). Without `queryKey` every key matches, so `{}` selects the whole cache.
381
+
382
+ ```ts
383
+ qc.remove({ predicate: (query) => Query.observerCountUnsafe(query) === 0 }); // everything not being read
384
+ ```
385
+
386
+ `handle.input` is the input of the latest factory call for that entry. An entry that was only hydrated, and not yet read or started on this client, has `undefined` input, so match on `key` to include those.
367
387
 
368
388
  Data can be `undefined` when the `queryFn`'s type allows it (`Promise<User | undefined>`); it's cached and reused like any other value, unlike in TanStack Query, where an `undefined` result is an error. So `getData` and an updater's `previous` return `undefined` both with no data and with `undefined` data; `Query.getUnsafe(qc.getQuery(factory, input)).hasData` tells them apart.
369
389
 
@@ -465,7 +485,7 @@ raf-query's cache is written in [Effect](https://effect.website): `QueryClient`
465
485
  - A `queryFn` can return an `Effect`. Cancelling the request interrupts it.
466
486
  - An Effect `queryFn`'s error type is the query's: `qc.effect.fetch(issueQuery, input)` fails with `IssueNotFound | Query.CancelledError`. `ErrorOf<TFactory>` names it; it's `unknown` for promises. A `queryFn` that throws instead of returning is a defect, and isn't retried.
467
487
  - `retry` accepts a `Schedule` as well as a count or predicate.
468
- - `qc.effect` has every verb as an Effect: `prefetch`, `ensure`, `fetch`, `invalidate`, `reset`, `remove`, `setData`, `getData` (an `Option`), `dehydrate`, `hydrate`. `watch` is a `Stream` of an entry's state, and `events` a `Stream` of cache events.
488
+ - `qc.effect` has every verb as an Effect: `prefetch`, `ensure`, `fetch`, `invalidate`, `reset`, `remove`, `setData`, `getData` (an `Option`), `isFetching` (a count), `dehydrate`, `hydrate`. `watch` is a `Stream` of an entry's state, and `events` a `Stream` of cache events.
469
489
  - SSR streaming is Effect too, and the integrations are thin wrappers over it. `dehydrateStream(options)` (scoped) returns the cache's `initial` state and a `Stream` of `updates`: entries that start or settle later, each sent once, batched per microtask. The stream ends when the scope closes. `hydrateStream(stream)` hydrates each state as it arrives. `Stream.toReadableStream` / `Stream.fromReadableStream` carry it over a web stream. The `sent` option (a `Set` of hashes) makes separate `dehydrate` calls of one request skip entries already sent.
470
490
  - Entries are a data type with module functions, as in Effect's own modules: `Query.fetch(query)`, `Query.refetch(query)`, `Query.invalidate(query)`, `Query.changes(query)`, and `Query.getUnsafe(query)` / `Query.subscribeUnsafe(query, listener)` for synchronous reads.
471
491
  - `QueryObserver` is a data type too: one reader's view of a query, as `useQuery` sees it (the controls and the promise, with `whilePending`, `refetchInterval` and the focus / reconnect options). `QueryObserver.make(query, options)` creates one, and `QueryObserver.changes(observer)` streams its results; while it runs, the query counts as read and polls on `refetchInterval`.
@@ -598,10 +618,11 @@ Both render nothing on the server, since the server's cache isn't the browser's.
598
618
  | `new QueryClient(config?)` | `config.defaults` (query options below), `config.onError`, `config.isServer`, `config.layer` ([services](#services)) |
599
619
  | `prefetch`, `ensure`, `fetch` | [Start queries](#starting-queries) |
600
620
  | `invalidate`, `setData`, `getData` | [Write and read the cache](#mutations) |
601
- | `reset(factory, input)` / `reset(filter)` | Drop data and errors; read queries suspend and refetch. Resolves when they settle |
602
- | `remove(factory, input)` / `remove(filter)` | Remove entries and abort their requests |
621
+ | `reset(factory, input)` / `reset(filter)` | Drop data and errors; read queries suspend and refetch. Resolves when they settle. [Filters](#filters) |
622
+ | `remove(factory, input)` / `remove(filter)` | Remove entries and abort their requests. [Filters](#filters) |
603
623
  | `effect` | The [Effect](#effect) `QueryCache` behind the client |
604
624
  | `subscribe(listener)` | Cache events: `added`, `updated`, `observers` (a reader subscribed or left), `removed`, and `failed` (with the `error`) |
625
+ | `isFetching(filter?)` | How many entries have a request in flight, optionally only those matching `{ queryKey, exact? }` |
605
626
  | `getAll()`, `getQuery(factory, input?)` | Cache entries, for devtools and integrations |
606
627
  | `clear()` | Drop every entry and abort in-flight requests |
607
628
  | `mount()` | Start window-focus and reconnect refetching. The providers call it |
@@ -653,6 +674,7 @@ In the browser, retries pause while `navigator.onLine` is `false`: after the ret
653
674
  | `useQueryClient()` | Read the client |
654
675
  | `useQuery(factory, handle, options?)` | `[Thenable<Data>, controls]`; for paged factories `Data` is `{ pages, pageParams }` and controls include paging |
655
676
  | `useWaterfall(factory, input)` | Start a query during render and return its handle |
677
+ | `useIsFetching(filter?)` | How many queries have a request in flight, re-rendering when it changes; for global loading indicators |
656
678
 
657
679
  ## Development
658
680
 
package/dist/cache.d.mts CHANGED
@@ -30,10 +30,21 @@ export type Event = {
30
30
  readonly query: Query;
31
31
  readonly type: "failed";
32
32
  };
33
- /** Matches cache entries by key prefix, or by exact key with `exact`. */
33
+ /**
34
+ * Selects cache entries: by key prefix (exact key with `exact`), then by
35
+ * `predicate`. Without `queryKey` every key matches, so `{}` selects the
36
+ * whole cache.
37
+ */
34
38
  export interface Filter {
35
39
  readonly exact?: boolean;
36
- readonly queryKey: QueryKey;
40
+ /**
41
+ * Keep only entries this returns `true` for; runs after key matching.
42
+ * `query.handle.input` is the input of the latest factory call, and stays
43
+ * `undefined` for an entry only hydrated so far; match on `query.key` to
44
+ * include those.
45
+ */
46
+ readonly predicate?: (query: Query) => boolean;
47
+ readonly queryKey?: QueryKey;
37
48
  }
38
49
  /** `ensure` / `fetch` arguments: the input, then load options for paged factories. */
39
50
  export type LoadArgs<TFactory extends QueryFactory> = InputArgs<TFactory> | [input: InputOf<TFactory>, options: LoadOptions<TFactory>];
@@ -98,6 +109,13 @@ export interface QueryCache {
98
109
  * screen.
99
110
  */
100
111
  invalidate<TFactory extends QueryFactory>(...target: Target<TFactory>): Effect.Effect<void>;
112
+ /**
113
+ * How many entries have a request in flight: all of them, or those
114
+ * matching `filter`. For global loading indicators.
115
+ */
116
+ isFetching(filter?: Filter): Effect.Effect<number>;
117
+ /** `isFetching`, synchronously, for renders. */
118
+ isFetchingUnsafe(filter?: Filter): number;
101
119
  readonly isServer: boolean;
102
120
  /**
103
121
  * Refetch read, stale queries on window focus and reconnect while the
package/dist/cache.mjs CHANGED
@@ -11,8 +11,9 @@ import { Clock, Context, Effect, Layer, Option, Predicate, RcRef, Stream } from
11
11
  /**
12
12
  * The query cache, as an Effect service. `make` builds one in the current
13
13
  * scope; closing the scope interrupts every request and timer it started.
14
- * Everything that waits, or changes the cache, is an Effect; `getQueryUnsafe`
15
- * and `subscribeUnsafe` are for renders and external stores.
14
+ * Everything that waits, or changes the cache, is an Effect; `getQueryUnsafe`,
15
+ * `isFetchingUnsafe` and `subscribeUnsafe` are for renders and external
16
+ * stores.
16
17
  *
17
18
  * Requests run with the services the cache was built with, under those of
18
19
  * the latest verb that called for the entry. So the verbs that can start a
@@ -44,6 +45,15 @@ function handleOf(entry) {
44
45
  function dataOf(entry) {
45
46
  return unsafeCast(entry.state.data);
46
47
  }
48
+ function keyMatcher(filter) {
49
+ const prefix = filter.queryKey;
50
+ if (prefix === void 0) return () => true;
51
+ if (filter.exact) {
52
+ const hash = hashKey(prefix);
53
+ return (entry) => entry.hash === hash;
54
+ }
55
+ return (entry) => matchesKey(entry.key, prefix);
56
+ }
47
57
  /**
48
58
  * Background refetch of cached data a verb reuses. A server cache renders
49
59
  * once, so a refetch there could only duplicate a request whose result is
@@ -113,8 +123,8 @@ const make = Effect.fnUntraced(function* (config = {}) {
113
123
  const entry = state.entries.get(hashKey(optionsFor(first, input).queryKey));
114
124
  return entry ? [entry] : [];
115
125
  }
116
- const hash = hashKey(first.queryKey);
117
- return [...state.entries.values()].filter((entry) => first.exact ? entry.hash === hash : matchesKey(entry.key, first.queryKey));
126
+ const keyMatches = keyMatcher(first);
127
+ return [...state.entries.values()].filter((entry) => keyMatches(entry) && (first.predicate?.(entry) ?? true));
118
128
  };
119
129
  const subscription = yield* RcRef.make({ acquire: Effect.acquireRelease(Effect.sync(() => platform.subscribeUnsafe((event) => {
120
130
  for (const entry of state.entries.values()) if (isObserved(entry)) onPlatformEvent(entry, event);
@@ -126,6 +136,7 @@ const make = Effect.fnUntraced(function* (config = {}) {
126
136
  };
127
137
  };
128
138
  const getQueryUnsafe = (factory, ...args) => typed(build(factory, args[0]));
139
+ const isFetchingUnsafe = (filter) => (filter ? match([filter]) : [...state.entries.values()]).filter((entry) => entry.state.isFetching).length;
129
140
  return {
130
141
  all: Effect.sync(() => [...state.entries.values()]),
131
142
  clear: Effect.sync(() => {
@@ -149,6 +160,8 @@ const make = Effect.fnUntraced(function* (config = {}) {
149
160
  hydrate: (dehydrated, options = {}) => Effect.sync(() => hydrateEntries(entryFor, dehydrated, options)),
150
161
  hydrateStream: (states, options = {}) => Stream.runForEach(states, (dehydrated) => Effect.sync(() => hydrateEntries(entryFor, dehydrated, options))),
151
162
  invalidate: (...target) => Effect.suspend(() => settleAll(match(target).map(invalidate))),
163
+ isFetching: (filter) => Effect.sync(() => isFetchingUnsafe(filter)),
164
+ isFetchingUnsafe,
152
165
  isServer: state.isServer,
153
166
  mount: state.isServer ? Effect.void : Effect.asVoid(RcRef.get(subscription)),
154
167
  prefetch: (factory, ...args) => Effect.map(buildFor(factory, args[0]), (entry) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raf-query/core",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Framework-agnostic core of raf-query, a render-as-you-fetch query library",
5
5
  "keywords": [
6
6
  "query",