Skip to content

Commit d86b13d

Browse files
committed
error based solution
1 parent 911a46e commit d86b13d

3 files changed

Lines changed: 70 additions & 27 deletions

File tree

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

Lines changed: 55 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,40 @@ type InnerLoadContext = {
3737
sync?: boolean
3838
}
3939

40+
const reason = 'Match removed before complete load'
41+
class MatchLoadCancelledError extends Error {
42+
constructor() {
43+
super(reason)
44+
this.name = 'MatchCancel'
45+
}
46+
}
47+
48+
export const isMatchLoadCancelledError = (
49+
err: unknown,
50+
): err is MatchLoadCancelledError => err instanceof MatchLoadCancelledError
51+
52+
const getMatchOrThrowCancelled = (
53+
inner: InnerLoadContext,
54+
matchId: string,
55+
cleanupMatch?: AnyRouteMatch,
56+
): AnyRouteMatch => {
57+
const match = inner.router.getMatch(matchId)
58+
if (match) return match as AnyRouteMatch
59+
if (cleanupMatch) {
60+
const s = cleanupMatch._nonReactive
61+
s.beforeLoadPromise?.resolve()
62+
s.loaderPromise?.resolve()
63+
s.loadPromise?.resolve()
64+
cleanupMatch.abortController.abort(reason)
65+
clearTimeout(s.pendingTimeout)
66+
s.beforeLoadPromise = undefined
67+
s.loaderPromise = undefined
68+
s.loadPromise = undefined
69+
s.pendingTimeout = undefined
70+
}
71+
throw new MatchLoadCancelledError()
72+
}
73+
4074
const triggerOnReady = (inner: InnerLoadContext): void | Promise<void> => {
4175
if (!inner.rendered) {
4276
inner.rendered = true
@@ -788,6 +822,8 @@ const loadRouteMatch = async (
788822
matchPromises: Array<Promise<AnyRouteMatch>>,
789823
index: number,
790824
): Promise<AnyRouteMatch> => {
825+
let cleanupMatch: AnyRouteMatch | undefined
826+
791827
async function handleLoader(
792828
preload: boolean,
793829
prevMatch: AnyRouteMatch,
@@ -868,21 +904,17 @@ const loadRouteMatch = async (
868904
inner.router.options.defaultStaleReloadMode) !== 'blocking'
869905

870906
if (shouldSkipLoader(inner, matchId)) {
871-
const match = inner.router.getMatch(matchId)
872-
if (!match) {
873-
return inner.matches[index]!
874-
}
907+
const match = getMatchOrThrowCancelled(inner, matchId, cleanupMatch)
908+
909+
cleanupMatch = match
875910

876911
syncMatchContext(inner, matchId, index)
877912

878913
if (isServer ?? inner.router.isServer) {
879914
return inner.router.getMatch(matchId)!
880915
}
881916
} else {
882-
const prevMatch = inner.router.getMatch(matchId)
883-
if (!prevMatch) {
884-
return inner.matches[index]!
885-
}
917+
const prevMatch = getMatchOrThrowCancelled(inner, matchId, cleanupMatch)
886918

887919
// This is where all of the stale-while-revalidate magic happens
888920
const activeIdAtIndex = inner.router.stores.matchesId.state[index]
@@ -912,10 +944,8 @@ const loadRouteMatch = async (
912944
return prevMatch
913945
}
914946
await prevMatch._nonReactive.loaderPromise
915-
const match = inner.router.getMatch(matchId)
916-
if (!match) {
917-
return inner.matches[index]!
918-
}
947+
const match = getMatchOrThrowCancelled(inner, matchId, cleanupMatch)
948+
cleanupMatch = match
919949

920950
const error = match._nonReactive.error || match.error
921951
if (error) {
@@ -934,10 +964,8 @@ const loadRouteMatch = async (
934964
} else {
935965
const nextPreload =
936966
preload && !inner.router.stores.activeMatchStoresById.has(matchId)
937-
const match = inner.router.getMatch(matchId)
938-
if (!match) {
939-
return inner.matches[index]!
940-
}
967+
const match = getMatchOrThrowCancelled(inner, matchId, cleanupMatch)
968+
cleanupMatch = match
941969

942970
match._nonReactive.loaderPromise = createControlledPromise<void>()
943971
if (nextPreload !== match.preload) {
@@ -950,11 +978,7 @@ const loadRouteMatch = async (
950978
await handleLoader(preload, prevMatch, previousRouteMatchId, match, route)
951979
}
952980
}
953-
const match = inner.router.getMatch(matchId)
954-
if (!match) {
955-
return inner.matches[index]!
956-
}
957-
981+
const match = getMatchOrThrowCancelled(inner, matchId, cleanupMatch)
958982
if (!loaderIsRunningAsync) {
959983
match._nonReactive.loaderPromise?.resolve()
960984
match._nonReactive.loadPromise?.resolve()
@@ -973,10 +997,8 @@ const loadRouteMatch = async (
973997
isFetching: nextIsFetching,
974998
invalid: false,
975999
}))
976-
return inner.router.getMatch(matchId) ?? match
977-
} else {
978-
return match
9791000
}
1001+
return match
9801002
}
9811003

9821004
export async function loadMatches(arg: {
@@ -1042,6 +1064,7 @@ export async function loadMatches(arg: {
10421064

10431065
let firstNotFound: NotFoundError | undefined
10441066
let firstUnhandledRejection: unknown
1067+
let firstCancelledMatch: MatchLoadCancelledError | undefined
10451068

10461069
for (let i = 0; i < maxIndexExclusive; i++) {
10471070
matchPromises.push(loadRouteMatch(inner, matchPromises, i))
@@ -1056,6 +1079,10 @@ export async function loadMatches(arg: {
10561079
if (result.status !== 'rejected') continue
10571080

10581081
const reason = result.reason
1082+
if (isMatchLoadCancelledError(reason)) {
1083+
firstCancelledMatch ??= reason
1084+
continue
1085+
}
10591086
if (isRedirect(reason)) {
10601087
throw reason
10611088
}
@@ -1066,6 +1093,10 @@ export async function loadMatches(arg: {
10661093
}
10671094
}
10681095

1096+
if (firstCancelledMatch) {
1097+
throw firstCancelledMatch
1098+
}
1099+
10691100
if (firstUnhandledRejection !== undefined) {
10701101
throw firstUnhandledRejection
10711102
}

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,12 @@ import { setupScrollRestoration } from './scroll-restoration'
3434
import { defaultParseSearch, defaultStringifySearch } from './searchParams'
3535
import { rootRouteId } from './root'
3636
import { isRedirect, redirect } from './redirect'
37-
import { loadMatches, loadRouteChunk, routeNeedsPreload } from './load-matches'
37+
import {
38+
isMatchLoadCancelledError,
39+
loadMatches,
40+
loadRouteChunk,
41+
routeNeedsPreload,
42+
} from './load-matches'
3843
import {
3944
composeRewrites,
4045
executeRewriteInput,
@@ -2852,6 +2857,9 @@ export class RouterCore<
28522857

28532858
return matches
28542859
} catch (err) {
2860+
if (isMatchLoadCancelledError(err)) {
2861+
return undefined
2862+
}
28552863
if (isRedirect(err)) {
28562864
if (err.options.reloadDocument) {
28572865
return undefined

‎packages/router-core/tests/load.test.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ describe('loader skip or exec', () => {
427427

428428
resolveLoader?.({ ok: true })
429429

430-
await preloadPromise
430+
await expect(preloadPromise).resolves.toBeUndefined()
431431
// the route load won't throw, but it will log errors to the console if any
432432
expect(consoleErrorSpy).not.toHaveBeenCalled()
433433

@@ -488,9 +488,13 @@ describe('loader skip or exec', () => {
488488

489489
resolveFooLoader?.({ ok: true })
490490

491-
await Promise.all([preloadPromise, invalidatePromise])
491+
const [preloadResult] = await Promise.all([
492+
preloadPromise,
493+
invalidatePromise,
494+
])
492495

493496
expect(barLoader).toHaveBeenCalledTimes(2)
497+
expect(preloadResult).toBeUndefined()
494498
// the route load won't throw, but it will log errors to the console if any
495499
expect(consoleErrorSpy).not.toHaveBeenCalled()
496500
expect(

0 commit comments

Comments
 (0)