Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions .changeset/query-retry-after-rejection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@solidjs/router": patch
---

Retry failed queries immediately when an error boundary resets, even within the preload cache's five-second freshness window.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,8 @@ A query:
3. Refetches reactively by key on action revalidation.
4. Serves as a back/forward cache for browser navigation up to 5 minutes; user-initiated navigation bypasses it.

After a query rejects in the browser, a subsequent read can fetch again immediately. For example, an `<Errored>` fallback can call `reset()` to retry the query.

Consume results directly with Solid primitives — there is no router-specific async wrapper:

```tsx
Expand Down
12 changes: 8 additions & 4 deletions src/data/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,9 @@ export function query<T extends (...args: any) => any>(fn: T, name: string): Cac
cached &&
cached[0] &&
(isServer ||
intent === "native" ||
cached[4].count ||
(!intent && isHydrating()) ||
Date.now() - cached[0] < PRELOAD_TIMEOUT)
(cached[0] > 0 &&
(intent === "native" || cached[4].count || Date.now() - cached[0] < PRELOAD_TIMEOUT)))
) {
if (tracking) {
cached[4].count++;
Expand Down Expand Up @@ -404,7 +403,12 @@ export function query<T extends (...args: any) => any>(fn: T, name: string): Cac
}
}
}
if (error) throw v;
if (error) {
// Hydration still needs the original rejection to claim the server fallback.
// A negative stamp marks it rejected: never fresh, still truthy.
if (!isServer && cached[1] === source) cached[0] = -1;
throw v;
}
// a superseded fetch or a query.set since must not overwrite the newer value
if (cached[1] === source) cached[2] = v;
return v;
Expand Down
63 changes: 54 additions & 9 deletions test/cached-error.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
// @vitest-environment jsdom
import { Errored, createMemo, type ParentProps } from "solid-js";
import { Errored, Loading, createMemo, type ParentProps } from "solid-js";
import { render } from "@solidjs/web";
import { vi } from "vitest";
import { createRouter, memoryHistory, query, useNavigate } from "../src/index.js";

const wait = (ms: number) => new Promise(r => setTimeout(r, ms));

describe("#385 error from cached preload stays an error", () => {
test("cache-hit calls reject with the original error", async () => {
// no owner on purpose: query skips the navigator and runs standalone
const failing = query(async () => {
throw new Error("boom-385");
}, "failing-direct");
const error = new Error("boom-385");
const fetch = vi.fn(async () => {
throw error;
});
const failing = query(fetch, "failing-direct");
const first = failing();
const cached = failing();

await expect(failing()).rejects.toThrow("boom-385");
// second call within the freshness window is a cache hit on the rejected promise
await expect(failing()).rejects.toThrow("boom-385");
await Promise.all([expect(first).rejects.toBe(error), expect(cached).rejects.toBe(error)]);
expect(fetch).toHaveBeenCalledTimes(1);
});

test("error surfaces via the boundary on cache-hit renders, never as a value", async () => {
Expand Down Expand Up @@ -70,8 +74,7 @@ describe("#385 error from cached preload stays an error", () => {
expect(caught.length).toBeGreaterThan(0);
expect((caught[0] as Error).message).toBe("boom-385-render");

// navigate away and back within the cache window — the cached rejected
// promise is served from cache on the return trip
// Navigate away and back within the cache window.
nav("/", { scroll: false });
await wait(50);
expect(root.innerHTML).toContain("home");
Expand All @@ -86,3 +89,45 @@ describe("#385 error from cached preload stays an error", () => {
dispose();
});
});

test("resetting an error boundary retries a rejected query immediately", async () => {
const fetchProduct = vi
.fn<() => Promise<string>>()
.mockRejectedValueOnce(new Error("transient failure"))
.mockResolvedValue("Product loaded");
const getProduct = query(fetchProduct, "retry-product");
const Product = () => {
const product = createMemo(() => getProduct());
return <p>{product()}</p>;
};
const Router = createRouter({
routes: [{ path: "/", component: Product }],
history: memoryHistory("/")
});
const root = document.createElement("div");
vi.useFakeTimers({ toFake: ["Date"] });
const dispose = render(
() => (
<Router>
{props => (
<Errored fallback={(_error, reset) => <button onClick={reset}>Retry</button>}>
<Loading fallback={<p>Loading</p>}>{props.children}</Loading>
</Errored>
)}
</Router>
),
root
);

try {
await vi.waitFor(() => expect(root.textContent).toBe("Retry"));
expect(fetchProduct).toHaveBeenCalledTimes(1);

root.querySelector("button")!.click();
await vi.waitFor(() => expect(root.textContent).toBe("Product loaded"), { timeout: 300 });
expect(fetchProduct).toHaveBeenCalledTimes(2);
} finally {
dispose();
vi.useRealTimers();
}
});
17 changes: 17 additions & 0 deletions test/data/query-flight-consumption.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,23 @@ describe("query cache freshness windows", () => {
});

describe("hydration flight-entry consumption", () => {
test("reuses a rejected flight during hydration and retries afterward", async () => {
const error = new Error("server query failed");
const revived = Object.assign(Promise.reject(error), { s: 2, v: error });
const fetchData = vi.fn(async () => "fresh-data");
const cachedFn = query(fetchData, "rejectedFlight");
(globalThis as any)._$HY = { r: { [cachedFn.keyFor()]: revived } };

hydrating = true;
await expect(cachedFn()).rejects.toBe(error);
await expect(cachedFn()).rejects.toBe(error);
expect(fetchData).not.toHaveBeenCalled();

hydrating = false;
await expect(cachedFn()).resolves.toBe("fresh-data");
expect(fetchData).toHaveBeenCalledTimes(1);
});

test("hydration burst adopts the flight entry and dedups, one-shot registry", async () => {
return createRoot(async () => {
seedFlightEntry("flightQuery[]", "server-data");
Expand Down
Loading