Skip to content

Commit 0600009

Browse files
perf(fetchium): hydrate synchronously from a sync store (#69)
* perf(fetchium): hydrate synchronously from a sync store and start the first fetch on a microtask A query activated against SyncQueryStore (MMKV on mobile) resolved with its cached value a microtask after activation, so the first React render showed a loading state and a second, sync-lane render showed the data. The first fetch then waited on setTimeout(0). Apply the cached value in the activating read when the store returns synchronously, and run the subscription and first fetch on a microtask, still outside the relay's computation. AsyncQueryStore keeps its async path. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(fetchium): rewrite this change's changesets for React developers Lead with what changes for an app using useQuery or fetchQuery, keep migration notes to a line or two, and drop internal detail. No source change. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): fetch an invalidated query whatever its staleTime invalidateQueries() sets updatedAt to 0, but isStale only treated undefined as stale, so with staleTime: Infinity an uncached query invalidated before its first fetch started made no request and stayed pending. An invalidation made before the cache loaded is also kept now, instead of being overwritten by the cached timestamp. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(fetchium): tighten comments Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(fetchium): cut and shorten comments Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): cancel a queued debounce when starting a fetch immediately Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 5c636ff commit 0600009

5 files changed

Lines changed: 513 additions & 45 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'fetchium': patch
3+
---
4+
5+
With `SyncQueryStore`, a cached query renders its data on the first render instead of showing a loading frame first.
6+
7+
- The first fetch starts on a microtask instead of after `setTimeout(0)`. Tests that wait for a loading state or count renders may need updating.
8+
- A cached entry that can't be loaded is treated as a cache miss and fetched. Previously a fresh-looking entry could leave the query pending without fetching.

‎packages/fetchium/src/QueryResult.ts‎

Lines changed: 60 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,17 @@ import {
1515
queryKeyFor,
1616
CachedQuery,
1717
} from './QueryClient.js';
18+
import type { MaybePromise } from './query-types.js';
1819
import { DEFAULT_GC_TIME } from './stores/shared.js';
1920
import { GcKeyType } from './GcManager.js';
2021
import { Query, QueryDefinition, type ResolvedRetryConfig, resolveRetryConfig } from './query.js';
2122
import { EntityInstance } from './EntityInstance.js';
2223
import { hashValue } from 'signalium/utils';
23-
import { sleep, withRetry } from './retry.js';
24+
import { withRetry } from './retry.js';
25+
26+
function isThenable<T>(value: MaybePromise<T>): value is Promise<T> {
27+
return typeof (value as { then?: unknown } | null | undefined)?.then === 'function';
28+
}
2429

2530
/**
2631
* Thin fetch/relay orchestrator. Data management (proxy, notifier, child refs,
@@ -252,27 +257,60 @@ export class QueryInstance<T extends Query> {
252257
);
253258
}
254259

255-
private async initialize(): Promise<void> {
256-
const qc = this.queryClient;
257-
const state = this.relayState;
258-
260+
/** Runs once, inside the read that first activates the relay. */
261+
private initialize(): void {
259262
this.initialized = true;
260263

261-
let cached: CachedQuery | undefined;
264+
let loaded: MaybePromise<CachedQuery | undefined>;
262265

263266
try {
264-
cached = await qc.loadCachedQuery(this.def, this.storageKey);
267+
loaded = this.queryClient.loadCachedQuery(this.def, this.storageKey);
268+
} catch (error) {
269+
this.discardCorruptCache(error);
270+
loaded = undefined;
271+
}
265272

266-
if (cached !== undefined) {
267-
this.updatedAt = cached.updatedAt;
268-
state.value = this.applyData(cached.value, false, false, cached.preloadedEntities);
269-
}
273+
if (isThenable(loaded)) {
274+
loaded.then(
275+
cached => {
276+
this.hydrate(cached);
277+
this.startSubscriptionAndFetch();
278+
},
279+
error => {
280+
this.discardCorruptCache(error);
281+
this.startSubscriptionAndFetch();
282+
},
283+
);
284+
} else {
285+
this.hydrate(loaded);
286+
// Adapter and app code must not touch signals while the relay is the current consumer.
287+
queueMicrotask(() => this.startSubscriptionAndFetch());
288+
}
289+
}
290+
291+
private discardCorruptCache(error: unknown): void {
292+
const qc = this.queryClient;
293+
qc.store.deleteQuery(this.storageKey);
294+
qc.getContext().log?.warn?.('Failed to initialize query, the query cache may be corrupted or invalid', error);
295+
}
296+
297+
private hydrate(cached: CachedQuery | undefined): void {
298+
if (cached === undefined) return;
299+
300+
try {
301+
// Keep an invalidation made before the cache loaded.
302+
if (this.updatedAt !== 0) this.updatedAt = cached.updatedAt;
303+
this.relayState.value = this.applyData(cached.value, false, false, cached.preloadedEntities);
270304
} catch (error) {
271-
qc.store.deleteQuery(this.storageKey);
272-
qc.getContext().log?.warn?.('Failed to initialize query, the query cache may be corrupted or invalid', error);
305+
// Never applied, so drop the timestamp and let the query fetch.
306+
this.updatedAt = undefined;
307+
this.discardCorruptCache(error);
273308
}
309+
}
274310

275-
if (this.isPaused) {
311+
private startSubscriptionAndFetch(): void {
312+
// If deactivated meanwhile, update() fetches on reactivation.
313+
if (!this._isActive || this.isPaused) {
276314
return;
277315
}
278316

@@ -282,13 +320,13 @@ export class QueryInstance<T extends Query> {
282320
// `send()` awaits.
283321
this.reconcileSubscription();
284322

285-
if (cached === undefined || this.isStale) {
286-
await sleep(0);
287-
if (this.isPaused) return;
323+
// refetch() may have started a fetch since activation.
324+
const fetchInFlight = this.relayState.isPending && this._abortController !== undefined;
325+
if (this.isStale && !fetchInFlight) {
288326
this.runQueryImmediately();
289327
}
290328
} catch (error) {
291-
state.setError(error as Error);
329+
this.relayState.setError(error as Error);
292330
}
293331
}
294332

@@ -377,6 +415,8 @@ export class QueryInstance<T extends Query> {
377415
}
378416

379417
private runQueryImmediately(): void {
418+
clearTimeout(this.debounceTimer);
419+
this.debounceTimer = undefined;
380420
this._abortController?.abort();
381421
this._abortController = new AbortController();
382422
this._fetchNextAbort?.abort();
@@ -491,7 +531,8 @@ export class QueryInstance<T extends Query> {
491531
// ======================================================
492532

493533
private get isStale(): boolean {
494-
if (this.updatedAt === undefined) {
534+
// 0 means invalidated, whatever the staleTime.
535+
if (this.updatedAt === undefined || this.updatedAt === 0) {
495536
return true;
496537
}
497538

‎packages/fetchium/src/__tests__/caching-persistence.test.ts‎

Lines changed: 14 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -230,19 +230,16 @@ describe('Caching and Persistence', () => {
230230

231231
await testWithClient(client, async () => {
232232
const relay = fetchQuery(GetItem, { id: '1' });
233-
// Force a pull
233+
// A synchronous store resolves the relay in the read that activates it.
234234
relay.value;
235-
await sleep();
236-
235+
expect(relay.isPending).toBe(false);
237236
expect(relay.value!).toMatchObject({ id: 1, name: 'Cached Data' });
237+
expect(await relay).toMatchObject({ id: 1, name: 'Cached Data' });
238238

239-
const result = await relay;
240-
241-
// Immediate value should be the same as the cached value because we're
242-
// background refetching but have a value that is still valid.
243-
expect(result).toMatchObject({ id: 1, name: 'Cached Data' });
239+
// The refetch starts a microtask later.
240+
await sleep();
241+
expect(relay.isPending).toBe(true);
244242
expect(relay.value!).toMatchObject({ id: 1, name: 'Cached Data' });
245-
expect(relay.isPending).toBe(false);
246243

247244
await sleep(20);
248245

@@ -277,19 +274,14 @@ describe('Caching and Persistence', () => {
277274

278275
await testWithClient(client2, async () => {
279276
const relay = fetchQuery(GetItem);
280-
// Force a pull
281277
relay.value;
282-
await sleep();
283-
278+
expect(relay.isPending).toBe(false);
284279
expect(relay.value!).toMatchObject({ id: 1, value: 'Persistent' });
280+
expect(await relay).toMatchObject({ id: 1, value: 'Persistent' });
285281

286-
const result = await relay;
287-
288-
// Immediate value should be the same as the cached value because we're
289-
// background refetching but have a value that is still valid.
290-
expect(result).toMatchObject({ id: 1, value: 'Persistent' });
282+
await sleep();
283+
expect(relay.isPending).toBe(true);
291284
expect(relay.value!).toMatchObject({ id: 1, value: 'Persistent' });
292-
expect(relay.isPending).toBe(false);
293285

294286
await sleep(30);
295287

@@ -380,19 +372,15 @@ describe('Caching and Persistence', () => {
380372

381373
await testWithClient(client, async () => {
382374
const relay = fetchQuery(GetDocument);
383-
// Force a pull
384375
relay.value;
385-
await sleep();
386-
376+
expect(relay.isPending).toBe(false);
387377
expect(relay.value!).toMatchObject({ user: { __typename: 'User', id: 1, name: 'Persisted User' } });
388-
389378
const result = await relay;
390-
391-
// Immediate value should be the same as the cached value because we're
392-
// background refetching but have a value that is still valid.
393379
expect(result).toMatchObject({ user: { __typename: 'User', id: 1, name: 'Persisted User' } });
380+
381+
await sleep();
382+
expect(relay.isPending).toBe(true);
394383
expect(relay.value!).toMatchObject({ user: { __typename: 'User', id: 1, name: 'Persisted User' } });
395-
expect(relay.isPending).toBe(false);
396384

397385
await sleep(20);
398386

0 commit comments

Comments
 (0)