Skip to content

Commit 3ba197b

Browse files
committed
fix(router-core): preserve retained beforeLoad context while pending
1 parent 3848503 commit 3ba197b

2 files changed

Lines changed: 165 additions & 1 deletion

File tree

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
import { cleanup, render, screen, waitFor } from '@testing-library/react'
2+
import { afterEach, expect, test } from 'vitest'
3+
import { createControlledPromise } from '@tanstack/router-core'
4+
import {
5+
Outlet,
6+
RouterProvider,
7+
createMemoryHistory,
8+
createRootRoute,
9+
createRoute,
10+
createRouter,
11+
} from '../src'
12+
13+
afterEach(cleanup)
14+
15+
// While a child route shows its pending fallback, ancestor routes stay mounted
16+
// and must keep the context their own `beforeLoad` produced. Losing it is not
17+
// cosmetic: ancestors that reach into a nested context value - the usual shape
18+
// for an auth/session context - throw while they are still on screen.
19+
test('retained ancestor keeps its beforeLoad context while a child route is pending', async () => {
20+
const childLoader = createControlledPromise<void>()
21+
// Errors thrown while rendering the mounted ancestor. Caught here only so the
22+
// failure surfaces as an assertion instead of taking out the route's error
23+
// boundary; in an app this is an uncaught render crash.
24+
const renderErrors: Array<string> = []
25+
26+
const rootRoute = createRootRoute({
27+
beforeLoad: () => ({ auth: { user: 'ada' } }),
28+
component: function RootLayout() {
29+
const { auth } = rootRoute.useRouteContext()
30+
let user
31+
try {
32+
user = auth.user
33+
} catch (error) {
34+
renderErrors.push(String(error))
35+
}
36+
return (
37+
<>
38+
<div>{`user:${user ?? 'MISSING'}`}</div>
39+
<Outlet />
40+
</>
41+
)
42+
},
43+
})
44+
const indexRoute = createRoute({
45+
getParentRoute: () => rootRoute,
46+
path: '/',
47+
component: () => <div>Home</div>,
48+
})
49+
const childRoute = createRoute({
50+
getParentRoute: () => rootRoute,
51+
path: '/child',
52+
pendingMs: 0,
53+
pendingComponent: () => <div>Pending</div>,
54+
loader: () => childLoader,
55+
component: () => <div>Child</div>,
56+
})
57+
const router = createRouter({
58+
routeTree: rootRoute.addChildren([indexRoute, childRoute]),
59+
history: createMemoryHistory({ initialEntries: ['/'] }),
60+
})
61+
62+
render(<RouterProvider router={router} />)
63+
await screen.findByText('Home')
64+
await waitFor(() => expect(router.state.status).toBe('idle'))
65+
66+
const navigation = router.navigate({ to: '/child' })
67+
await screen.findByText('Pending')
68+
69+
expect(renderErrors).toEqual([])
70+
expect(screen.getByText('user:ada')).toBeInTheDocument()
71+
72+
childLoader.resolve()
73+
await navigation
74+
})
75+
76+
// Contextualization walks the lane serially, so an ancestor whose `beforeLoad`
77+
// is still in flight parks the walk above every deeper ancestor. The pending
78+
// fallback is published from that parked state, so the ancestors the walk has
79+
// not reached yet must already be presentable.
80+
test('retained ancestor keeps its beforeLoad context while an ancestor above it is pending', async () => {
81+
const childLoader = createControlledPromise<void>()
82+
const rootBeforeLoad = createControlledPromise<void>()
83+
let rootResolved = false
84+
const renderErrors: Array<string> = []
85+
86+
const rootRoute = createRootRoute({
87+
beforeLoad: async () => {
88+
// Only the navigation blocks; the initial load must settle normally.
89+
if (rootResolved) {
90+
await rootBeforeLoad
91+
}
92+
rootResolved = true
93+
return { session: 'live' }
94+
},
95+
component: () => <Outlet />,
96+
})
97+
const dashRoute = createRoute({
98+
getParentRoute: () => rootRoute,
99+
path: '/dash',
100+
beforeLoad: () => ({ auth: { user: 'ada' } }),
101+
component: function DashLayout() {
102+
const { auth } = dashRoute.useRouteContext()
103+
let user
104+
try {
105+
user = auth.user
106+
} catch (error) {
107+
renderErrors.push(String(error))
108+
}
109+
return (
110+
<>
111+
<div>{`user:${user ?? 'MISSING'}`}</div>
112+
<Outlet />
113+
</>
114+
)
115+
},
116+
})
117+
const overviewRoute = createRoute({
118+
getParentRoute: () => dashRoute,
119+
path: 'overview',
120+
component: () => <div>Overview</div>,
121+
})
122+
const detailRoute = createRoute({
123+
getParentRoute: () => dashRoute,
124+
path: 'detail',
125+
pendingMs: 0,
126+
pendingComponent: () => <div>Pending</div>,
127+
loader: () => childLoader,
128+
component: () => <div>Detail</div>,
129+
})
130+
const router = createRouter({
131+
routeTree: rootRoute.addChildren([
132+
dashRoute.addChildren([overviewRoute, detailRoute]),
133+
]),
134+
history: createMemoryHistory({ initialEntries: ['/dash/overview'] }),
135+
})
136+
137+
render(<RouterProvider router={router} />)
138+
await screen.findByText('Overview')
139+
await waitFor(() => expect(router.state.status).toBe('idle'))
140+
141+
const navigation = router.navigate({ to: '/dash/detail' })
142+
await screen.findByText('Pending')
143+
144+
expect(renderErrors).toEqual([])
145+
expect(screen.getByText('user:ada')).toBeInTheDocument()
146+
147+
rootBeforeLoad.resolve()
148+
childLoader.resolve()
149+
await navigation
150+
})

‎packages/router-core/src/load-client.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,12 @@ async function contextualize(
362362
const [location, matches] = lane
363363
const signal = options[0 /* controller */].signal
364364
const preload = !!options[4 /* preload */]
365+
for (let index = 0; index < retainedEnd; index++) {
366+
const retained = options[3 /* base */][index]?.context
367+
if (retained) {
368+
matches[index]!.context = retained
369+
}
370+
}
365371
for (let index = options[7 /* resolvedPrefix */] ?? 0; index < end; index++) {
366372
const match = matches[index]!
367373
const route = getRoute(router, match)
@@ -397,8 +403,13 @@ async function contextualize(
397403
...parentContext,
398404
...routeContext,
399405
}
400-
match.context = context
406+
const retained =
407+
index < retainedEnd && route.options.beforeLoad
408+
? options[3 /* base */][index]?.context
409+
: undefined
410+
match.context = retained ?? context
401411
} catch (cause) {
412+
match.context = context
402413
releaseFlight(router, match)
403414
return [index, normalizeLaneError(route, cause, options)]
404415
}
@@ -408,6 +419,7 @@ async function contextualize(
408419
}
409420
const validationError = match.paramsError ?? match.searchError
410421
if (validationError !== undefined) {
422+
match.context = context
411423
releaseFlight(router, match)
412424
return [index, normalizeLaneError(route, validationError, options)]
413425
}
@@ -448,6 +460,7 @@ async function contextualize(
448460
}
449461
const outcome = normalize(result, false, route.id)
450462
if (outcome[0 /* kind */] !== SUCCESS) {
463+
match.context = context
451464
releaseFlight(router, match)
452465
return [index, outcome]
453466
}
@@ -456,6 +469,7 @@ async function contextualize(
456469
...result,
457470
}
458471
} catch (cause) {
472+
match.context = context
459473
releaseFlight(router, match)
460474
return [index, normalizeLaneError(route, cause, options)]
461475
} finally {

0 commit comments

Comments
 (0)