fix(router): context issues #1907
Mergedtannerlinsleymerged 41 commits into
main fromrefs/pull/1907/headmerged by schiller-manuel(GitHub profile, opens in a new tab) - packages/react-router/src/router.ts line 1551@@ -1545,3 +1543,4 @@15451543 location: next,15461544 checkLatest: () => this.checkLatest(promise),15471545 onReady: async () => {1546+ // eslint-disable-next-line ts/require-await
- @@ -1806,15 +1788,15 @@1806- handleRedirectAndNotFound(match, err)1788+ handleRedirectAndNotFound(getMatch(), err)18071789 }180817901809- matches[index] = match = updateMatch(match.id, () => ({1810- ...match,1791+ updateMatch(matchId, (prev) => ({1792+ ...prev,18111793 error: err,18121794 status: 'error',18131795 updatedAt: Date.now(),18141796 abortController: new AbortController(),18151797 }))18161798 }181717991818- if (match.paramsError) {1819- handleSerialError(match.paramsError, 'PARSE_PARAMS')1820- }1800+ const runBeforeLoad = async () => {1801+ if (getMatch().beforeLoadPromise) {1802+ return await getMatch().beforeLoadPromise!
- @@ -383,0 +397,21 @@397+ return { mock }398+ },399+ loader: async ({ context }) => {400+ await sleep(WAIT_TIME)401+ context.mock()402+ },403+ })404+405+ const routeTree = rootRoute.addChildren([aboutRoute, indexRoute])406+ const router = createRouter({ routeTree, context: { foo: 'bar' } })407+408+ await router.load()409+410+ // Don't await, simulate user clicking before preload is done411+ router.preloadRoute(aboutRoute)412+413+ await router.navigate(aboutRoute)414+ await router.invalidate()415+416+ // Expect double call: once from preload, once from navigate417+ expect(mock).toHaveBeenCalledTimes(2)
SeanCassiere reviewed
OutdatedResolvedby SeanCassiere@@ -3,3 +3,4 @@3344 export const Route = createFileRoute('/about')({55 component: AboutComponent,6+ beforeLoad: async () => {Resolvedby SeanCassiere@@ -0,0 +36,21 @@36+}37+38+describe('preload: matched routes', { timeout: 20000 }, () => {39+ it('should wait for lazy options to be streamed in before ', async () => {40+ const { router } = createTestRouter(41+ createMemoryHistory({ initialEntries: ['/'] }),42+ )43+44+ await router.load()45+46+ // Preload the route and navigate to it47+ router.preloadRoute({ to: '/heavy' })48+ await router.navigate({ to: '/heavy' })49+50+ await router.invalidate()51+52+ expect(router.state.location.pathname).toBe('/heavy')53+54+ const lazyRoute = router.routesByPath['/heavy']55+56+ expect(lazyRoute.options.component).toBeDefined()@@ -381,3 +381,16 @@381381 expect(mock).toHaveBeenCalledTimes(1)382382 })383383384+ test("on navigate (with preload), loader isn't invoked with undefined context if beforeLoad is pending when navigation happens", async () => {385+ const mock = vi.fn()386+387+ const rootRoute = createRootRoute()388+ const indexRoute = createRoute({389+ getParentRoute: () => rootRoute,390+ path: '/',391+ })392+ const aboutRoute = createRoute({393+ getParentRoute: () => rootRoute,394+ path: '/about',395+ beforeLoad: async () => {396+ await sleep(WAIT_TIME) // Use a longer delay hereResolvedby SeanCassiere@@ -383,0 +391,21 @@391+ })392+ const aboutRoute = createRoute({393+ getParentRoute: () => rootRoute,394+ path: '/about',395+ beforeLoad: async () => {396+ await sleep(WAIT_TIME) // Use a longer delay here397+ return { mock }398+ },399+ loader: async ({ context }) => {400+ await sleep(WAIT_TIME)401+ context.mock()402+ },403+ })404+405+ const routeTree = rootRoute.addChildren([aboutRoute, indexRoute])406+ const router = createRouter({ routeTree, context: { foo: 'bar' } })407+408+ await router.load()409+410+ // Don't await, simulate user clicking before preload is done411+ router.preloadRoute(aboutRoute)@@ -183,3 +183,4 @@183183 PathParamError,184184 getInitialRouterState,185185 defaultSerializeError,186+ getRouteMatch,OutdatedResolvedby SeanCassiere@@ -1828,10 +1807,15 @@1828- parentMatch?.context ?? this.options.context ?? {}1807+ const previousResolve = loadPromise.resolve1808+ loadPromise = createControlledPromise<void>(previousResolve)182918091830- // Make sure the match has parent context set before going further1831- matches[index] = match = {1832- ...match,1810+ const parentContext = getParentContext()1811+1812+ updateMatch(matchId, (prev) => ({1813+ ...prev,1814+ isFetching: 'beforeLoad',1815+ beforeLoadPromise,1816+ loadPromise,18331817 routeContext: replaceEqualDeep(1834- match.routeContext,1818+ prev.routeContext,18351819 parentContext,18361820 ),1837- context: replaceEqualDeep(match.context, parentContext),1821+ context: replaceEqualDeep(prev.context, parentContext),OutdatedResolvedby SeanCassiere@@ -1881,0 +1895,21 @@1895+ setTimeout(() => {1896+ try {1897+ checkLatest()1898+ // Update the match and prematurely resolve the loadMatches promise so that1899+ // the pending component can start rendering1900+ triggerOnReady()1901+ } catch {}1902+ }, pendingMs)1903+ }1904+1905+ const { paramsError, searchError } = getMatch()1906+1907+ if (paramsError) {1908+ handleSerialError(paramsError, 'PARSE_PARAMS')1909+ }1910+1911+ if (searchError) {1912+ handleSerialError(searchError, 'VALIDATE_SEARCH')1913+ }1914+1915+ try {OutdatedResolvedby tannerlinsley@@ -1905,6 +1929,15 @@1905- location,1906- navigate: (opts) =>1907- this.navigate({ ...opts, _fromLocation: location }),1908- cause: preload ? 'preload' : match.cause,1909- route,1910- }1929+ validResolvedMatches.forEach(1930+ ({ id: matchId, routeId, params: p }, index) => {1931+ const getMatch = () => getRouteMatch(this.state, matchId)!1932+1933+ const createValidateResolvedMatchPromise = async () => {1934+ const parentMatchPromise = matchPromises[index - 1]1935+ const route = this.looseRoutesById[routeId]!1936+1937+ const {1938+ params,1939+ loaderDeps,1940+ abortController,1941+ context,1942+ cause,1943+ } = getMatch()OutdatedResolvedby SeanCassiere@@ -1892,19 +1928,3 @@189219281893- validResolvedMatches.forEach((match, index) => {1894- const createValidateResolvedMatchPromise = async () => {1895- const parentMatchPromise = matchPromises[index - 1]1896- const route = this.looseRoutesById[match.routeId]!1897-1898- const loaderContext: LoaderFnContext = {1899- params: match.params,1900- deps: match.loaderDeps,1901- preload: !!preload,1902- parentMatchPromise,1903- abortController: match.abortController,1904- context: match.context,1905- location,1906- navigate: (opts) =>1907- this.navigate({ ...opts, _fromLocation: location }),1908- cause: preload ? 'preload' : match.cause,1909- route,1910- }1929+ validResolvedMatches.forEach(1930+ ({ id: matchId, routeId, params: p }, index) => {OutdatedResolvedby tannerlinsley@@ -2079,11 +2149,10 @@2079- const shouldReload =2080- typeof shouldReloadOption === 'function'2081- ? shouldReloadOption(loaderContext)2082- : shouldReloadOption2083-2084- matches[index] = match = {2085- ...match,2086- preload:2087- !!preload &&2088- !this.state.matches.find((d) => d.id === match.id),2089- }2149+ // If the route is successful and still fresh, just resolve2150+ const { status, invalid } = getMatch()2151+2152+ if (2153+ status === 'success' &&2154+ (invalid || (shouldReload ?? age > staleAge))2155+ ) {2156+ ;(async () => {2157+ try {2158+ await fetchWithRedirectAndNotFound()chorobin(GitHub profile, opens in a new tab) approved these changes
KyleSanderson(GitHub profile, opens in a new tab) approved these changes
SeanCassiere reviewed
OutdatedResolvedby tannerlinsley@@ -2010,11 +1959,12 @@1959+ ...prev,1960+ beforeLoadPromise: undefined,1961+ isFetching: false,1962+ }1963+ })1964+ }1965+ }201019662011- const meta = route.options.meta?.({2012- matches,2013- match,2014- params: match.params,2015- loaderData,2016- })1967+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex)1968+ const matchPromises: Array<Promise<any>> = []201719692018- const headers = route.options.headers?.({2019- loaderData,2020- })1970+ await Promise.all(Resolvedby tannerlinsley@@ -7,3 +7,4 @@77 }88 export interface RouterHistory {99 location: HistoryLocation10+ subscribers: Set<() => void>schiller-manuel(GitHub profile, opens in a new tab) approved these changes
Sign in to join this conversation.



☁️ Nx Cloud Report#
CI is running/has finished running commands for commit 50f0b4aa6a58e7fb56ab5db3f0074944122f1f17. As they complete they will appear below. Click to see the status, the terminal output, and the build insights.
📂 See all runs for this CI Pipeline Execution
✅ Successfully ran 3 targets
nx affected --targets=test:format,test:eslint,test:unit,test:types,test:build,build --parallel=3nx run-many --target=test:e2e:replaynx run-many --target=build --exclude=examples/**Sent with 💌 from NxCloud.