Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for client side context #12515

Open
wants to merge 7 commits into
base: dev
Choose a base branch
from
Open
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/spa-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router": minor
---

Add `context` support to client side data routers (`createBrowsertRouter`, etc.)
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ packages/react-router-dom/server.d.ts
packages/react-router-dom/server.js
packages/react-router-dom/server.mjs
tutorial/dist/
public/
100 changes: 66 additions & 34 deletions integration/browser-entry-test.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,12 @@
import { test, expect } from "@playwright/test";

import type { AppFixture, Fixture } from "./helpers/create-fixture.js";
import {
createFixture,
js,
createAppFixture,
} from "./helpers/create-fixture.js";
import { PlaywrightFixture } from "./helpers/playwright-fixture.js";

let fixture: Fixture;
let appFixture: AppFixture;

test.beforeAll(async () => {
fixture = await createFixture({
files: {
"app/routes/_index.tsx": js`
import { Link } from "react-router";

export default function Index() {
return (
<div>
<div id="pizza">pizza</div>
<Link to="/burgers">burger link</Link>
</div>
)
}
`,

"app/routes/burgers.tsx": js`
export default function Index() {
return <div id="cheeseburger">cheeseburger</div>;
}
`,
},
});

// This creates an interactive app using puppeteer.
appFixture = await createAppFixture(fixture);
});

test.afterAll(() => appFixture.close());

test(
"expect to be able to browse backward out of a remix app, then forward " +
"twice in history and have pages render correctly",
Expand All @@ -50,6 +16,32 @@ test(
"FireFox doesn't support browsing to an empty page (aka about:blank)"
);

let fixture = await createFixture({
files: {
"app/routes/_index.tsx": js`
import { Link } from "react-router";

export default function Index() {
return (
<div>
<div id="pizza">pizza</div>
<Link to="/burgers">burger link</Link>
</div>
)
}
`,

"app/routes/burgers.tsx": js`
export default function Index() {
return <div id="cheeseburger">cheeseburger</div>;
}
`,
},
});

// This creates an interactive app using puppeteer.
let appFixture = await createAppFixture(fixture);

let app = new PlaywrightFixture(appFixture, page);

// Slow down the entry chunk on the second load so the bug surfaces
Expand Down Expand Up @@ -84,5 +76,45 @@ test(
// successfully render /burgers
await page.waitForSelector("#cheeseburger");
expect(await app.getHtml()).toContain("cheeseburger");

appFixture.close();
}
);

test("allows users to pass a client side context to HydratedRouter", async ({
page,
}) => {
let fixture = await createFixture({
files: {
"app/entry.client.tsx": js`
import { HydratedRouter } from "react-router/dom";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";

startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<HydratedRouter context={{ foo: 'bar' }} />
</StrictMode>
);
});
`,
"app/routes/_index.tsx": js`
export function clientLoader({ context }) {
return context;
}
export default function Index({ loaderData }) {
return <h1>Hello, {loaderData.foo}</h1>
}
`,
},
});

let appFixture = await createAppFixture(fixture);
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/", true);
expect(await app.getHtml()).toContain("Hello, bar");

appFixture.close();
});
179 changes: 179 additions & 0 deletions packages/react-router/__tests__/router/context-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import { createMemoryHistory } from "../../lib/router/history";
import { createRouter } from "../../lib/router/router";
import type { DataStrategyResult } from "../../lib/router/utils";
import { cleanup } from "./utils/data-router-setup";
import { createFormData, tick } from "./utils/utils";

describe("router context", () => {
it("provides context to loaders and actions", async () => {
let context = { count: 1 };
let router = createRouter({
history: createMemoryHistory(),
context,
routes: [
{
path: "/",
},
{
id: "a",
path: "/a",
loader({ context }) {
return ++context.count;
},
},
{
id: "b",
path: "/b",
action({ context }) {
return ++context.count;
},
loader({ context }) {
return ++context.count;
},
},
],
});

await router.navigate("/a");
expect(router.state.loaderData.a).toBe(2);
expect(context.count).toBe(2);

await router.navigate("/b", {
formMethod: "post",
formData: createFormData({}),
});
expect(router.state.actionData?.b).toBe(3);
expect(router.state.loaderData.b).toBe(4);
expect(context.count).toBe(4);

cleanup(router);
});

it("works with dataStrategy for a sequential implementation", async () => {
let context = {};
let router = createRouter({
history: createMemoryHistory(),
context,
routes: [
{
path: "/",
},
{
id: "parent",
path: "/parent",
async loader({ context }) {
// Ensure these actually run sequentially :)
await tick();
context.parent = "PARENT MIDDLEWARE";
return "PARENT";
},
children: [
{
id: "child",
path: "child",
loader({ context }) {
context.parent += " (amended from child)";
context.child = "CHILD MIDDLEWARE";
return "CHILD";
},
},
],
},
],
async dataStrategy({ matches }) {
let keyedResults: Record<string, DataStrategyResult> = {};
for (let m of matches) {
keyedResults[m.route.id] = await m.resolve();
}
return keyedResults;
},
});

await router.navigate("/parent/child");

expect(router.state.loaderData).toEqual({
child: "CHILD",
parent: "PARENT",
});
expect(context).toEqual({
child: "CHILD MIDDLEWARE",
parent: "PARENT MIDDLEWARE (amended from child)",
});

cleanup(router);
});

it("works with dataStrategy for an easy middleware implementation", async () => {
let context = {};
let router = createRouter({
history: createMemoryHistory(),
context,
routes: [
{
path: "/",
},
{
id: "parent",
path: "/parent",
loader: ({ context }) => ({ contextSnapshot: { ...context } }),
handle: {
middleware(context) {
context.parent = "PARENT MIDDLEWARE";
},
},
children: [
{
id: "child",
path: "child",
loader: ({ context }) => ({ contextSnapshot: { ...context } }),
handle: {
middleware(context) {
context.parent += " (amended from child)";
context.child = "CHILD MIDDLEWARE";
},
},
},
],
},
],
async dataStrategy({ context, matches }) {
// Run middleware sequentially
for (let m of matches) {
await m.route.handle.middleware(context);
}

// Run loaders in parallel
let keyedResults: Record<string, DataStrategyResult> = {};
await Promise.all(
matches.map(async (m) => {
keyedResults[m.route.id] = await m.resolve();
})
);
return keyedResults;
},
});

await router.navigate("/parent/child");

expect(router.state.loaderData).toEqual({
child: {
contextSnapshot: {
child: "CHILD MIDDLEWARE",
parent: "PARENT MIDDLEWARE (amended from child)",
},
},
parent: {
contextSnapshot: {
child: "CHILD MIDDLEWARE",
parent: "PARENT MIDDLEWARE (amended from child)",
},
},
});
expect(context).toEqual({
child: "CHILD MIDDLEWARE",
parent: "PARENT MIDDLEWARE (amended from child)",
});

cleanup(router);
});
});
8 changes: 8 additions & 0 deletions packages/react-router/__tests__/router/fetchers-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ describe("fetchers", () => {
request: new Request("http://localhost/foo", {
signal: A.loaders.root.stub.mock.calls[0][0].request.signal,
}),
context: {},
});
});
});
Expand Down Expand Up @@ -3189,6 +3190,7 @@ describe("fetchers", () => {
expect(F.actions.root.stub).toHaveBeenCalledWith({
params: {},
request: expect.any(Request),
context: {},
});

let request = F.actions.root.stub.mock.calls[0][0].request;
Expand Down Expand Up @@ -3217,6 +3219,7 @@ describe("fetchers", () => {
expect(F.actions.root.stub).toHaveBeenCalledWith({
params: {},
request: expect.any(Request),
context: {},
});

let request = F.actions.root.stub.mock.calls[0][0].request;
Expand All @@ -3243,6 +3246,7 @@ describe("fetchers", () => {
expect(F.actions.root.stub).toHaveBeenCalledWith({
params: {},
request: expect.any(Request),
context: {},
});

let request = F.actions.root.stub.mock.calls[0][0].request;
Expand All @@ -3269,6 +3273,7 @@ describe("fetchers", () => {
expect(F.actions.root.stub).toHaveBeenCalledWith({
params: {},
request: expect.any(Request),
context: {},
});

let request = F.actions.root.stub.mock.calls[0][0].request;
Expand Down Expand Up @@ -3296,6 +3301,7 @@ describe("fetchers", () => {
expect(F.actions.root.stub).toHaveBeenCalledWith({
params: {},
request: expect.any(Request),
context: {},
});

let request = F.actions.root.stub.mock.calls[0][0].request;
Expand Down Expand Up @@ -3325,6 +3331,7 @@ describe("fetchers", () => {
expect(F.actions.root.stub).toHaveBeenCalledWith({
params: {},
request: expect.any(Request),
context: {},
});

let request = F.actions.root.stub.mock.calls[0][0].request;
Expand Down Expand Up @@ -3353,6 +3360,7 @@ describe("fetchers", () => {
expect(F.actions.root.stub).toHaveBeenCalledWith({
params: {},
request: expect.any(Request),
context: {},
});

let request = F.actions.root.stub.mock.calls[0][0].request;
Expand Down
Loading
Loading