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 6 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/
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
7 changes: 7 additions & 0 deletions packages/react-router/__tests__/router/router-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1320,6 +1320,7 @@ describe("a router", () => {
request: new Request("http://localhost/tasks", {
signal: nav.loaders.tasks.stub.mock.calls[0][0].request.signal,
}),
context: {},
});

let nav2 = await t.navigate("/tasks/1");
Expand All @@ -1328,6 +1329,7 @@ describe("a router", () => {
request: new Request("http://localhost/tasks/1", {
signal: nav2.loaders.tasksId.stub.mock.calls[0][0].request.signal,
}),
context: {},
});

let nav3 = await t.navigate("/tasks?foo=bar#hash");
Expand All @@ -1336,6 +1338,7 @@ describe("a router", () => {
request: new Request("http://localhost/tasks?foo=bar", {
signal: nav3.loaders.tasks.stub.mock.calls[0][0].request.signal,
}),
context: {},
});

let nav4 = await t.navigate("/tasks#hash", {
Expand All @@ -1346,6 +1349,7 @@ describe("a router", () => {
request: new Request("http://localhost/tasks?foo=bar", {
signal: nav4.loaders.tasks.stub.mock.calls[0][0].request.signal,
}),
context: {},
});

expect(t.router.state.navigation.formAction).toBe("/tasks");
Expand Down Expand Up @@ -1743,6 +1747,7 @@ describe("a router", () => {
expect(nav.actions.tasks.stub).toHaveBeenCalledWith({
params: {},
request: expect.any(Request),
context: {},
});

// Assert request internals, cannot do a deep comparison above since some
Expand Down Expand Up @@ -1786,6 +1791,7 @@ describe("a router", () => {
expect(nav.actions.tasks.stub).toHaveBeenCalledWith({
params: {},
request: expect.any(Request),
context: {},
});
// Assert request internals, cannot do a deep comparison above since some
// internals aren't the same on separate creations
Expand Down Expand Up @@ -1818,6 +1824,7 @@ describe("a router", () => {
expect(nav.actions.tasks.stub).toHaveBeenCalledWith({
params: {},
request: expect.any(Request),
context: {},
});

// Assert request internals, cannot do a deep comparison above since some
Expand Down
6 changes: 6 additions & 0 deletions packages/react-router/__tests__/router/submission-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -948,6 +948,7 @@ describe("submissions", () => {
expect(nav.actions.root.stub).toHaveBeenCalledWith({
params: {},
request: expect.any(Request),
context: {},
});

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

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

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

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

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

let request = nav.actions.root.stub.mock.calls[0][0].request;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
import type {
AgnosticDataRouteObject,
AgnosticRouteMatch,
DefaultRouterContext,
} from "../../../lib/router/utils";
import { createRouter, IDLE_FETCHER } from "../../../lib/router/router";
import {
Expand Down Expand Up @@ -144,6 +145,7 @@ type SetupOpts = {
initialIndex?: number;
hydrationData?: HydrationState;
dataStrategy?: DataStrategyFunction;
context?: DefaultRouterContext;
};

// We use a slightly modified version of createDeferred here that includes the
Expand Down Expand Up @@ -199,6 +201,7 @@ export function setup({
initialIndex,
hydrationData,
dataStrategy,
context,
}: SetupOpts) {
let guid = 0;
// Global "active" helpers, keyed by navType:guid:loaderOrAction:routeId.
Expand Down Expand Up @@ -335,6 +338,7 @@ export function setup({
jest.spyOn(history, "replace");
currentRouter = createRouter({
basename,
context,
history,
routes: enhanceRoutes(routes),
hydrationData,
Expand Down
Loading
Loading