Skip to content

Commit 7f40ee2

Browse files
authored
feat(fetchium): add an enabled option to useQuery (#85)
* feat(fetchium): add an `enabled` option to `useQuery` * fix(docs): remove trailing whitespace from useQuery example * feat(fetchium): show cached data from disabled `useQuery` * fix(fetchium): keep disabled `useQuery` cache reads across remounts and param changes
1 parent 92e9dce commit 7f40ee2

9 files changed

Lines changed: 885 additions & 15 deletions

File tree

‎.changeset/use-query-enabled.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'fetchium': minor
3+
---
4+
5+
Add an `enabled` option to `useQuery`: `useQuery(Query, params, { enabled })`. It defaults to `true`. A disabled query never fetches or subscribes, but still reads the cache, like TanStack Query's `enabled: false`. With cached data, in memory or in the persistent store within `cacheTime`, it starts resolved with that data, even if stale. Without cached data it stays pending and sends no request. The cached value stays live: entity updates and fetches by enabled readers of the same query show up in it. Setting `enabled` to `true` activates the query with the current params, and doesn't refetch a cache that is still within `staleTime`. For queries without params, pass `undefined` as the second argument.

‎docs/src/app/api/fetchium-react/page.md‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,19 @@ import { useQuery, useSuspenseQuery } from 'fetchium/react';
2121
function useQuery<T extends Query>(
2222
QueryClass: new () => T,
2323
params?: ExtractQueryParams<T>,
24+
options?: { enabled?: boolean },
2425
): QueryPromise<T>;
2526
```
2627

2728
React hook for fetching a query. Subscribes the component to the query's reactive state, re-rendering when the query result changes. Internally uses Signalium's `useReactive` (deep-by-default in v3) to bridge the reactive signal system with React's rendering cycle.
2829

2930
#### Parameters
3031

31-
| Parameter | Type | Description |
32-
| ------------ | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
33-
| `QueryClass` | `new () => T` | The query class to instantiate and execute. Must extend `Query` or `RESTQuery`. |
34-
| `params` | `ExtractQueryParams<T>` | Parameters matching the query's `params` shape. Optional if the query has no required params. Values can be Signalium `Signal`s for reactive parameter changes. |
32+
| Parameter | Type | Description |
33+
| ----------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
34+
| `QueryClass` | `new () => T` | The query class to instantiate and execute. Must extend `Query` or `RESTQuery`. |
35+
| `params` | `ExtractQueryParams<T>` | Parameters matching the query's `params` shape. Optional if the query has no required params. Values can be Signalium `Signal`s for reactive parameter changes. |
36+
| `options.enabled` | `boolean` | Defaults to `true`. When `false`, skips fetching and subscribing to the query, but still returns cached data when there is some. |
3537

3638
#### Returns
3739

@@ -128,6 +130,36 @@ const SearchResults = component(() => {
128130
});
129131
```
130132

133+
#### Conditional queries
134+
135+
```tsx
136+
function UserProfile({
137+
userId,
138+
enabled,
139+
}: {
140+
userId: string;
141+
enabled: boolean;
142+
}) {
143+
const query = useQuery(GetUser, { id: userId }, { enabled });
144+
145+
// A disabled query still shows cached data.
146+
if (query.isReady) {
147+
return <div>{query.value.name}</div>;
148+
}
149+
150+
return (
151+
<div>{enabled ? 'Loading...' : 'Select a user to load their profile.'}</div>
152+
);
153+
}
154+
```
155+
156+
A disabled query never fetches or subscribes, but it still reads the cache:
157+
158+
- If the query has cached data (in memory, or in the persistent store and within its `cacheTime`), the result starts resolved: `isReady: true`, `isResolved: true`, `isPending: false`, with `value` set to the cached data. Stale data is shown as-is. It is not refetched while disabled.
159+
- If there is no cached data, the result stays `isPending: true` with `value: undefined` and no request is made.
160+
161+
The cached value stays reactive. Entity updates and fetches by enabled consumers of the same query appear in the disabled result. Setting `enabled` to `true` activates the query with the current parameters. Setting it back to `false` releases this hook's subscription; other consumers of the same query remain active. For queries without parameters, pass `undefined` as the second argument: `useQuery(GetUsers, undefined, { enabled })`.
162+
131163
#### Notes
132164

133165
- `useQuery` is a thin wrapper around Signalium v3's `useReactive`, which is deep-by-default. It returns a **structurally-shared snapshot** of the query result, so memoized children that receive subtrees as props keep stable references when the underlying data is unchanged.

‎packages/fetchium/src/QueryClient.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,25 @@ export class QueryClient {
414414
return queryInstance.relay;
415415
}
416416

417+
/**
418+
* Like `getQuery`, but the returned promise never fetches or subscribes: it
419+
* resolves with the cached value (in memory or persisted), or stays pending
420+
* when there is none. Backs `useQuery(..., { enabled: false })`.
421+
* @internal
422+
*/
423+
peekQuery<T extends Query>(
424+
queryDef: QueryDefinition<any, any, any>,
425+
params: QueryParams | undefined,
426+
): QueryPromise<T> {
427+
const queryKey = queryKeyFor(queryDef, params);
428+
let queryInstance = this.queryInstances.get(queryKey) as QueryInstance<T> | undefined;
429+
if (queryInstance === undefined) {
430+
queryInstance = new QueryInstance(queryDef, this, queryKey, params);
431+
this.queryInstances.set(queryKey, queryInstance as QueryInstance<any>);
432+
}
433+
return queryInstance.peekRelay as QueryPromise<T>;
434+
}
435+
417436
// ======================================================
418437
// Leases (retain / prefetch)
419438
// ======================================================

‎packages/fetchium/src/QueryResult.ts‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
type DeactivateOptions,
88
settled,
99
isSignal,
10+
notifier,
1011
} from 'signalium';
1112
import { NetworkMode, type QueryResult, type EntityDef } from './types.js';
1213
import {
@@ -64,6 +65,12 @@ export class QueryInstance<T extends Query> {
6465
/** The public-facing ReactivePromise returned to consumers. */
6566
readonly relay: ReactivePromise<QueryResult<T>>;
6667

68+
/**
69+
* Read-only view for disabled consumers: resolves with the cached value, if
70+
* any, without fetching or subscribing. Stays pending when nothing is cached.
71+
*/
72+
readonly peekRelay: ReactivePromise<QueryResult<T>>;
73+
6774
private queryClient: QueryClient;
6875
private initialized: boolean = false;
6976
private updatedAt: number | undefined = undefined;
@@ -74,6 +81,13 @@ export class QueryInstance<T extends Query> {
7481

7582
private _relayState: RelayState<QueryResult<T>> | undefined = undefined;
7683
private _isActive: boolean = false;
84+
/** A disabled consumer is reading `peekRelay`. Holds off GC like `_isActive`. */
85+
private _isPeeking: boolean = false;
86+
/** Storage key `peek()` last loaded the persistent cache for. */
87+
private peekLoadedKey: number = -1;
88+
private readonly peekNotifier = notifier();
89+
/** Storage key of the params `rootEntity` was applied for. */
90+
private rootStorageKey: number = -1;
7791
private wasPaused: boolean = false;
7892
private reconnectsAtDeactivate: number = 0;
7993
private reconnectsAtLastFetch: number;
@@ -372,8 +386,116 @@ export class QueryInstance<T extends Query> {
372386
},
373387
{ desc: `Query(${def.statics.id})` },
374388
);
389+
390+
this.peekRelay = relay<QueryResult<T>>(
391+
state => {
392+
this._isPeeking = true;
393+
this.peek(state, true);
394+
return {
395+
update: () => this.peek(state, false),
396+
deactivate: () => {
397+
this._isPeeking = false;
398+
if (!this._isActive) {
399+
this.scheduleGc();
400+
}
401+
},
402+
};
403+
},
404+
{ desc: `QueryPeek(${def.statics.id})` },
405+
);
375406
}
376407

408+
/**
409+
* Shows the root entity's value. While the query is inactive and holds nothing
410+
* for the current params, it loads them from the persistent cache first. Never
411+
* fetches. The parsed root belongs to the instance, so GC owns it and a later
412+
* activation picks up from it.
413+
*/
414+
private peek(state: RelayState<QueryResult<T>>, activating: boolean): void {
415+
// Applied data (a cache load or another consumer's fetch) reruns this.
416+
this.peekNotifier.consume();
417+
if (this.stoppedByDestroy()) {
418+
return;
419+
}
420+
const extractedParams = extractParamsForKey(this.params);
421+
const storageKey = queryKeyFor(this.def, extractedParams);
422+
// An active query loads its own data. A load that settles after this reader
423+
// unmounted still applies, so a remount doesn't load again.
424+
const loadCache = !this._isActive && this.rootStorageKey !== storageKey && this.peekLoadedKey !== storageKey;
425+
426+
if (loadCache && !this.initialized && storageKey !== this.storageKey) {
427+
this.adoptParams(extractedParams, storageKey);
428+
}
429+
if (activating) {
430+
// Resolve config first so this cancels in the bucket GC was scheduled in.
431+
this.getOrCreateExecutionContext();
432+
this.queryClient.gcManager.cancel(this.queryKey, this.config?.gcTime ?? DEFAULT_GC_TIME);
433+
}
434+
435+
if (loadCache) {
436+
this.peekLoadedKey = storageKey;
437+
const { destroyCount, fetchStarts, initialized } = this;
438+
const apply = (cached: CachedQuery | undefined): void => {
439+
if (cached === undefined || this.stoppedByDestroy() || this.destroyCount !== destroyCount) {
440+
return;
441+
}
442+
// Fetched, or moved off these params, while loading.
443+
if (
444+
this.fetchStarts !== fetchStarts ||
445+
queryKeyFor(this.def, extractParamsForKey(this.params)) !== storageKey
446+
) {
447+
return;
448+
}
449+
try {
450+
if (storageKey !== this.storageKey) {
451+
this.adoptParams(extractedParams, storageKey);
452+
this.getOrCreateExecutionContext();
453+
}
454+
const value = this.applyData(cached.value, false, false, cached.preloadedEntities);
455+
if (initialized) {
456+
// The inactive relay takes these params' data, so reactivating refetches only if stale.
457+
this.updatedAt = cached.updatedAt;
458+
this.relayState.value = value;
459+
}
460+
} catch (error) {
461+
this.discardCorruptCache(error, storageKey);
462+
}
463+
};
464+
465+
let loaded: MaybePromise<CachedQuery | undefined>;
466+
try {
467+
loaded = this.queryClient.loadCachedQuery(this.def, storageKey);
468+
} catch (error) {
469+
this.discardCorruptCache(error, storageKey);
470+
loaded = undefined;
471+
}
472+
if (isThenable(loaded)) {
473+
loaded.then(apply, error => {
474+
if (!this.stoppedByDestroy()) {
475+
this.discardCorruptCache(error, storageKey);
476+
}
477+
});
478+
} else {
479+
apply(loaded);
480+
}
481+
}
482+
483+
const root = this.rootEntity;
484+
if (root !== undefined && this.rootStorageKey === storageKey) {
485+
const value = root.getProxy(this.def.statics.shape as unknown as EntityDef) as QueryResult<T>;
486+
if (state.isPending || state.value !== value) {
487+
state.value = value;
488+
}
489+
} else if (!state.isPending) {
490+
// Signal params moved to a key with nothing loaded.
491+
state.setPromise(new Promise<never>(() => {}));
492+
}
493+
}
494+
495+
private notifyPeek = (): void => {
496+
this.peekNotifier.notify();
497+
};
498+
377499
/** Apply raw data (fresh or cached) to the root entity and return the proxy. */
378500
private applyData(
379501
data: unknown,
@@ -391,6 +513,11 @@ export class QueryInstance<T extends Query> {
391513
appendMode,
392514
preloadedEntities,
393515
);
516+
this.rootStorageKey = this.storageKey;
517+
// Not synchronously: this can run inside the main relay's or a proxy's read.
518+
if (this._isPeeking) {
519+
queueMicrotask(this.notifyPeek);
520+
}
394521

395522
if (previousRoot !== undefined && previousRoot !== this.rootEntity && !def.statics.isEntityResult) {
396523
this.queryClient.releaseQueryRoot(previousRoot, this);
@@ -710,6 +837,10 @@ export class QueryInstance<T extends Query> {
710837
}
711838

712839
private scheduleGc(): void {
840+
// A disabled consumer still shows the cached value. Its deactivation schedules GC.
841+
if (this._isPeeking) {
842+
return;
843+
}
713844
const gcTime = this.config?.gcTime ?? DEFAULT_GC_TIME;
714845
this.queryClient.gcManager.schedule(this.queryKey, gcTime, GcKeyType.Query);
715846
}

‎packages/fetchium/src/__tests__/activation-timing.test.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, it, expect, afterEach, vi } from 'vitest';
2-
import { reactive, signal, watcher, withContexts } from 'signalium';
2+
import { reactive, settled, signal, watcher, withContexts } from 'signalium';
33
import { MemoryPersistentStore, SyncQueryStore } from '../stores/sync.js';
44
import { AsyncQueryStore, type AsyncPersistentStore } from '../stores/async.js';
55
import { poll } from '../subscriptions/polling.js';
@@ -617,6 +617,7 @@ describe('A topic query mounted and unmounted in one task', () => {
617617
describe('A topic query unmounted before its first data, in a later task', () => {
618618
const hadWindow = 'window' in globalThis;
619619
afterEach(() => {
620+
vi.useRealTimers();
620621
if (!hadWindow) delete (globalThis as any).window;
621622
});
622623

@@ -631,21 +632,28 @@ describe('A topic query unmounted before its first data, in a later task', () =>
631632
}
632633

633634
it('is pending, not rejected, when mounted again, until its data lands', async () => {
635+
await settled();
636+
vi.useFakeTimers();
634637
const client = makeTopicClient(new MemoryPersistentStore());
635-
const { relay } = await mountAndLeave(client);
636-
await sleep(20);
638+
let relay: any;
639+
const first = activate(client, () => (relay = fetchQuery(GetPrices)).isPending);
640+
// Flush activation, then unmount before the topic's 5 ms response.
641+
await vi.advanceTimersByTimeAsync(2);
642+
first();
643+
await vi.advanceTimersByTimeAsync(20);
637644
expect(relay.isRejected).toBe(false);
638645

639646
const reads: ReturnType<typeof state>[] = [];
640647
const second = activate(client, () => reads.push(state(fetchQuery(GetPrices))));
641648
expect(reads[0]).toEqual({ isPending: true, isRejected: false, value: undefined });
642-
await sleep(3);
649+
await vi.advanceTimersByTimeAsync(3);
643650
expect(state(relay)).toEqual({ isPending: true, isRejected: false, value: undefined });
644-
await sleep(30);
651+
await vi.advanceTimersByTimeAsync(30);
645652
expect(reads.some(r => r.isRejected)).toBe(false);
646653
expect(state(relay)).toEqual({ isPending: false, isRejected: false, value: 'data:prices' });
647654
second();
648655
client.destroy();
656+
await vi.advanceTimersByTimeAsync(0);
649657
});
650658

651659
it('settles an awaiter of the first mount with the data a later mount brings', async () => {

0 commit comments

Comments
 (0)