Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/sync-hydrate-first-fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'fetchium': patch
---

With `SyncQueryStore`, a cached query renders its data on the first render instead of showing a loading frame first.

- 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.
- 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.
89 changes: 71 additions & 18 deletions packages/fetchium/src/QueryResult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,17 @@ import {
queryKeyFor,
CachedQuery,
} from './QueryClient.js';
import type { MaybePromise } from './query-types.js';
import { DEFAULT_GC_TIME } from './stores/shared.js';
import { GcKeyType } from './GcManager.js';
import { Query, QueryDefinition, type ResolvedRetryConfig, resolveRetryConfig } from './query.js';
import { EntityInstance } from './EntityInstance.js';
import { hashValue } from 'signalium/utils';
import { sleep, withRetry } from './retry.js';
import { withRetry } from './retry.js';

function isThenable<T>(value: MaybePromise<T>): value is Promise<T> {
return typeof (value as { then?: unknown } | null | undefined)?.then === 'function';
}

/**
* Thin fetch/relay orchestrator. Data management (proxy, notifier, child refs,
Expand Down Expand Up @@ -252,27 +257,75 @@ export class QueryInstance<T extends Query> {
);
}

private async initialize(): Promise<void> {
const qc = this.queryClient;
const state = this.relayState;

/**
* Runs once, from the relay's first activation. That activation happens
* inside the read that watched the relay (for React, during render).
*
* When the store answers synchronously (SyncQueryStore), the cached value is
* applied right here, so the activating read, and the first render, already
* see it. Subscribing and fetching wait for the next microtask: both call
* into adapter and app code that may read or write signals, which must not
* run while the relay's computation is the current consumer. A microtask
* rather than a timer keeps the first fetch off the macrotask queue.
*
* With an asynchronous store (AsyncQueryStore), the cache resolves on a later
* tick, outside the activating read, and everything runs from there.
*/
private initialize(): void {
this.initialized = true;

let cached: CachedQuery | undefined;
let loaded: MaybePromise<CachedQuery | undefined>;

try {
cached = await qc.loadCachedQuery(this.def, this.storageKey);
loaded = this.queryClient.loadCachedQuery(this.def, this.storageKey);
} catch (error) {
this.discardCorruptCache(error);
loaded = undefined;
}

if (cached !== undefined) {
this.updatedAt = cached.updatedAt;
state.value = this.applyData(cached.value, false, false, cached.preloadedEntities);
}
if (isThenable(loaded)) {
loaded.then(
cached => {
this.hydrate(cached);
this.startSubscriptionAndFetch();
},
error => {
this.discardCorruptCache(error);
this.startSubscriptionAndFetch();
},
);
} else {
this.hydrate(loaded);
queueMicrotask(() => this.startSubscriptionAndFetch());
}
}

private discardCorruptCache(error: unknown): void {
const qc = this.queryClient;
qc.store.deleteQuery(this.storageKey);
qc.getContext().log?.warn?.('Failed to initialize query, the query cache may be corrupted or invalid', error);
}

/** Resolves the relay with a cached value. */
private hydrate(cached: CachedQuery | undefined): void {
if (cached === undefined) return;

try {
this.updatedAt = cached.updatedAt;
this.relayState.value = this.applyData(cached.value, false, false, cached.preloadedEntities);
} catch (error) {
qc.store.deleteQuery(this.storageKey);
qc.getContext().log?.warn?.('Failed to initialize query, the query cache may be corrupted or invalid', error);
// Unusable entry: treat it as a miss so the query still fetches, instead
// of trusting a timestamp whose data was never applied.
this.updatedAt = undefined;
this.discardCorruptCache(error);
}
}

if (this.isPaused) {
/** Starts the subscription, then the first fetch if there is no fresh cached value. */
private startSubscriptionAndFetch(): void {
// Deactivated in the meantime: update() fetches on reactivation, since the
// relay is still pending (or stale) with no fetch in flight.
if (!this._isActive || this.isPaused) {
return;
}

Expand All @@ -282,13 +335,13 @@ export class QueryInstance<T extends Query> {
// `send()` awaits.
this.reconcileSubscription();

if (cached === undefined || this.isStale) {
await sleep(0);
if (this.isPaused) return;
// Skip if something already started a fetch since activation (refetch()).
const fetchInFlight = this.relayState.isPending && this._abortController !== undefined;
if (this.isStale && !fetchInFlight) {
Comment thread
abedell-phantom marked this conversation as resolved.
Resolved
this.runQueryImmediately();
Comment thread
abedell-phantom marked this conversation as resolved.
Resolved
}
} catch (error) {
state.setError(error as Error);
this.relayState.setError(error as Error);
}
}

Expand Down
50 changes: 24 additions & 26 deletions packages/fetchium/src/__tests__/caching-persistence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,19 +230,18 @@ describe('Caching and Persistence', () => {

await testWithClient(client, async () => {
const relay = fetchQuery(GetItem, { id: '1' });
// Force a pull
// A synchronous store resolves the relay with the cached value in the
// read that activates it, so awaiting it yields the cached value.
relay.value;
await sleep();

expect(relay.isPending).toBe(false);
expect(relay.value!).toMatchObject({ id: 1, name: 'Cached Data' });
expect(await relay).toMatchObject({ id: 1, name: 'Cached Data' });

const result = await relay;

// Immediate value should be the same as the cached value because we're
// background refetching but have a value that is still valid.
expect(result).toMatchObject({ id: 1, name: 'Cached Data' });
// The background refetch starts a microtask later; the cached value
// stays visible while it is in flight.
await sleep();
expect(relay.isPending).toBe(true);
expect(relay.value!).toMatchObject({ id: 1, name: 'Cached Data' });
expect(relay.isPending).toBe(false);

await sleep(20);

Expand Down Expand Up @@ -277,19 +276,18 @@ describe('Caching and Persistence', () => {

await testWithClient(client2, async () => {
const relay = fetchQuery(GetItem);
// Force a pull
// A synchronous store resolves the relay with the cached value in the
// read that activates it, so awaiting it yields the cached value.
relay.value;
await sleep();

expect(relay.isPending).toBe(false);
expect(relay.value!).toMatchObject({ id: 1, value: 'Persistent' });
expect(await relay).toMatchObject({ id: 1, value: 'Persistent' });

const result = await relay;

// Immediate value should be the same as the cached value because we're
// background refetching but have a value that is still valid.
expect(result).toMatchObject({ id: 1, value: 'Persistent' });
// The background refetch starts a microtask later; the cached value
// stays visible while it is in flight.
await sleep();
expect(relay.isPending).toBe(true);
expect(relay.value!).toMatchObject({ id: 1, value: 'Persistent' });
expect(relay.isPending).toBe(false);

await sleep(30);

Expand Down Expand Up @@ -380,19 +378,19 @@ describe('Caching and Persistence', () => {

await testWithClient(client, async () => {
const relay = fetchQuery(GetDocument);
// Force a pull
// A synchronous store resolves the relay with the cached value in the
// read that activates it, so awaiting it yields the cached value.
relay.value;
await sleep();

expect(relay.isPending).toBe(false);
expect(relay.value!).toMatchObject({ user: { __typename: 'User', id: 1, name: 'Persisted User' } });

const result = await relay;

// Immediate value should be the same as the cached value because we're
// background refetching but have a value that is still valid.
expect(result).toMatchObject({ user: { __typename: 'User', id: 1, name: 'Persisted User' } });

// The background refetch starts a microtask later; the cached value
// stays visible while it is in flight.
await sleep();
expect(relay.isPending).toBe(true);
expect(relay.value!).toMatchObject({ user: { __typename: 'User', id: 1, name: 'Persisted User' } });
expect(relay.isPending).toBe(false);

await sleep(20);

Expand Down
Loading
Loading