From 96197d06540750c751cce666a42b35a2aa94dea0 Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Mon, 30 Jan 2023 00:04:40 -0700 Subject: [PATCH] fix: onLoad idempotency for search + context --- .../kitchen-sink-single-file/src/main.tsx | 3 +- packages/actions/src/index.ts | 8 +- packages/loaders/src/index.ts | 10 +- packages/react-loaders/src/index.tsx | 2 +- packages/router/src/link.ts | 4 - packages/router/src/route.ts | 12 +- packages/router/src/routeMatch.ts | 177 +++++++++++------- packages/router/src/router.ts | 52 ++--- 8 files changed, 156 insertions(+), 112 deletions(-) diff --git a/examples/react/kitchen-sink-single-file/src/main.tsx b/examples/react/kitchen-sink-single-file/src/main.tsx index 9962c255ee..73712ddca8 100644 --- a/examples/react/kitchen-sink-single-file/src/main.tsx +++ b/examples/react/kitchen-sink-single-file/src/main.tsx @@ -940,8 +940,7 @@ const router = new ReactRouter({ ), onRouteChange: () => { - createInvoiceAction.clear() - updateInvoiceAction.clear() + actionClient.clearAll() }, }) diff --git a/packages/actions/src/index.ts b/packages/actions/src/index.ts index 6d577f8b57..20b9e2cbf0 100644 --- a/packages/actions/src/index.ts +++ b/packages/actions/src/index.ts @@ -71,6 +71,12 @@ export class ActionClient< if (!this.initialized) this.init() return this.actions[opts.key as any] as any } + + clearAll = () => { + Object.keys(this.actions).forEach((key) => { + this.actions[key]!.clear() + }) + } } export type ActionByKey< @@ -168,7 +174,7 @@ export class Action< // await Promise.all(this.#promises) this.store.setState((s) => ({ ...s, - submissions: s.submissions.filter((d) => d.status !== 'pending'), + submissions: s.submissions.filter((d) => d.status === 'pending'), })) } diff --git a/packages/loaders/src/index.ts b/packages/loaders/src/index.ts index 0fe6d42864..1457599a9b 100644 --- a/packages/loaders/src/index.ts +++ b/packages/loaders/src/index.ts @@ -524,7 +524,7 @@ export class LoaderInstance< } // If we already have data, return it - if (this.state.status === 'success') { + if (typeof this.state.data !== 'undefined') { return this.state.data! } @@ -599,8 +599,6 @@ export class LoaderInstance< isFetching: false, })) - delete this.__loadPromise - if ((newer = hasNewer())) { await this.loader.options.onLatestSettled?.(this) return newer @@ -688,10 +686,16 @@ export class LoaderInstance< status: 'error', })) + await after() + throw err } }) + this.__loadPromise.then(() => { + delete this.__loadPromise + }) + return this.__loadPromise } } diff --git a/packages/react-loaders/src/index.tsx b/packages/react-loaders/src/index.tsx index ec2cffe8d3..af409a1ca9 100644 --- a/packages/react-loaders/src/index.tsx +++ b/packages/react-loaders/src/index.tsx @@ -113,7 +113,7 @@ export function useLoaderInstance< if (allOpts?.strict ?? true) { invariant( - loaderInstance.state.status === 'success', + typeof loaderInstance.state.data !== undefined, `useLoaderInstance: Loader instance { key: ${loader.key}, variables: ${allOpts.variables} }) is currently in a "${loaderInstance.state.status}" state. By default useLoaderInstance will throw an error if the loader instance is not in a "success" state. To avoid this error: diff --git a/packages/router/src/link.ts b/packages/router/src/link.ts index a00a14a90e..ca39f859de 100644 --- a/packages/router/src/link.ts +++ b/packages/router/src/link.ts @@ -252,10 +252,6 @@ export type LinkOptions< activeOptions?: ActiveOptions // If set, will preload the linked route on hover and cache it for this many milliseconds in hopes that the user will eventually navigate there. preload?: false | 'intent' - // When preloaded, the preloaded result will be considered "fresh" for this duration in milliseconds - preloadMaxAge?: number - // When preloaded and subsequently inactive, the preloaded result will remain in memory for this duration in milliseconds - preloadGcMaxAge?: number // Delay intent preloading by this many milliseconds. If the intent exits before this delay, the preload will be cancelled. preloadDelay?: number // If true, will render the link without the href attribute diff --git a/packages/router/src/route.ts b/packages/router/src/route.ts index ec9883abcc..b3462fad10 100644 --- a/packages/router/src/route.ts +++ b/packages/router/src/route.ts @@ -80,7 +80,13 @@ export type RouteOptions< }) => Promise | void // An asynchronous function responsible for preparing or fetching data for the route before it is rendered - onLoad?: OnLoadFn + onLoad?: OnLoadFn< + TSearchSchema, + TFullSearchSchema, + TAllParams, + TRouteContext, + TContext + > // This function will be called if the route's loader throws an error **during an attempted navigation**. // If you want to redirect due to an error, call `router.navigate()` from within this function. @@ -164,12 +170,14 @@ export type ParentParams = AnyPathParams extends TParentParams } export type OnLoadFn< + TSearchSchema extends AnySearchSchema = {}, TFullSearchSchema extends AnySearchSchema = {}, TAllParams extends AnyPathParams = {}, TContext extends AnyContext = AnyContext, TAllContext extends AnyContext = AnyContext, > = ( loaderContext: LoaderContext< + TSearchSchema, TFullSearchSchema, TAllParams, TContext, @@ -178,12 +186,14 @@ export type OnLoadFn< ) => Promise | void export interface LoaderContext< + TSearchSchema extends AnySearchSchema = {}, TFullSearchSchema extends AnySearchSchema = {}, TAllParams extends AnyPathParams = {}, TContext extends AnyContext = AnyContext, TAllContext extends AnyContext = AnyContext, > { params: TAllParams + routeSearch: TSearchSchema search: TFullSearchSchema signal?: AbortSignal preload: boolean diff --git a/packages/router/src/routeMatch.ts b/packages/router/src/routeMatch.ts index e75a77ace2..c1fc803dbb 100644 --- a/packages/router/src/routeMatch.ts +++ b/packages/router/src/routeMatch.ts @@ -1,10 +1,10 @@ import { Store } from '@tanstack/store' // import { GetFrameworkGeneric } from './frameworks' -import { AnyRoute, Route } from './route' +import { AnyRoute, AnySearchSchema, Route } from './route' import { AnyRoutesInfo, DefaultRoutesInfo } from './routeInfo' -import { AnyRouter, Router } from './router' -import { Expand, pick } from './utils' +import { AnyRouter, ParsedLocation, Router } from './router' +import { Expand, pick, replaceEqualDeep } from './utils' export interface RouteMatchStore< TRoutesInfo extends AnyRoutesInfo = DefaultRoutesInfo, @@ -24,6 +24,12 @@ const componentTypes = [ 'pendingComponent', ] as const +export interface PendingRouteMatchInfo { + state: RouteMatchStore + routeContext: {} + context: {} +} + export interface AnyRouteMatch extends RouteMatch {} export class RouteMatch< @@ -46,6 +52,7 @@ export class RouteMatch< abortController = new AbortController() onLoaderDataListeners = new Set<() => void>() parentMatch?: RouteMatch + pendingInfo?: PendingRouteMatchInfo __loadPromise?: Promise __onExit?: @@ -102,12 +109,30 @@ export class RouteMatch< ) } - __init = (opts: { parentMatch?: RouteMatch }) => { - // Validate the search params and stabilize them - this.parentMatch = opts.parentMatch + __commit = () => { + const { routeSearch, search, context, routeContext } = this.#resolveInfo({ + location: this.router.state.currentLocation, + }) + this.context = context + this.routeContext = routeContext + this.store.setState((s) => ({ + ...s, + routeSearch: replaceEqualDeep(s.routeSearch, routeSearch), + search: replaceEqualDeep(s.search, search), + })) + } - const parentSearch = - this.parentMatch?.state.search ?? this.router.state.latestLocation.search + cancel = () => { + this.abortController?.abort() + } + + #resolveSearchInfo = (opts: { + location: ParsedLocation + }): { routeSearch: {}; search: {} } => { + // Validate the search params and stabilize them + const parentSearchInfo = this.parentMatch + ? this.parentMatch.#resolveSearchInfo(opts) + : { search: opts.location.search, routeSearch: opts.location.search } try { const validator = @@ -115,40 +140,17 @@ export class RouteMatch< ? this.route.options.validateSearch.parse : this.route.options.validateSearch - let nextSearch = validator?.(parentSearch) ?? {} + const routeSearch = validator?.(parentSearchInfo.search) ?? {} - this.store.setState((s) => ({ - ...s, - routeSearch: nextSearch, - search: { - ...parentSearch, - ...nextSearch, - } as any, - })) + const search = { + ...parentSearchInfo.search, + ...routeSearch, + } - componentTypes.map(async (type) => { - const component = this.route.options[type] - - if (typeof this[type] !== 'function') { - this[type] = component - } - }) - - const parent = this.parentMatch - - this.routeContext = - this.route.options.getContext?.({ - parentContext: parent?.routeContext, - context: parent?.context, - params: this.params, - search: this.state.search, - }) || ({} as any) - - this.context = ( - parent - ? { ...parent.context, ...this.routeContext } - : { ...this.router?.options.context, ...this.routeContext } - ) as any + return { + routeSearch, + search, + } } catch (err: any) { console.error(err) const error = new (Error as any)('Invalid search params found', { @@ -156,31 +158,73 @@ export class RouteMatch< }) error.code = 'INVALID_SEARCH_PARAMS' + throw error + } + } + + #resolveInfo = (opts: { location: ParsedLocation }) => { + const { search, routeSearch } = this.#resolveSearchInfo(opts) + + const routeContext = + this.route.options.getContext?.({ + parentContext: this.parentMatch?.routeContext ?? {}, + context: + this.parentMatch?.context ?? this.router?.options.context ?? {}, + params: this.params, + search, + }) || ({} as any) + + const context = { + ...(this.parentMatch?.context ?? this.router?.options.context), + ...routeContext, + } as any + + return { + routeSearch, + search, + context, + routeContext, + } + } + + __load = async (opts: { + parentMatch: RouteMatch | undefined + preload?: boolean + location: ParsedLocation + }): Promise => { + this.parentMatch = opts.parentMatch + + let info + + try { + info = this.#resolveInfo(opts) + } catch (err) { this.store.setState((s) => ({ ...s, status: 'error', - error: error, + error: err, })) // Do not proceed with loading the route return } - } - cancel = () => { - this.abortController?.abort() - } + const { routeSearch, search, context, routeContext } = info + + componentTypes.map(async (type) => { + const component = this.route.options[type] + + if (typeof this[type] !== 'function') { + this[type] = component + } + }) - load = async (opts?: { preload?: boolean }): Promise => { // If the match is invalid, errored or idle, trigger it to load - if (this.state.status !== 'pending') { - await this.fetch(opts) + if (this.state.status === 'pending') { + return } - } - #latestId = '' - - fetch = async (opts?: { preload?: boolean }): Promise => { + // TODO: Should load promises be tracked based on location? this.__loadPromise = Promise.resolve().then(async () => { const loadId = '' + Date.now() + Math.random() this.#latestId = loadId @@ -191,17 +235,15 @@ export class RouteMatch< let latestPromise - this.store.batch(() => { - // If the match was in an error state, set it - // to a loading state again. Otherwise, keep it - // as loading or resolved - if (this.state.status === 'idle') { - this.store.setState((s) => ({ - ...s, - status: 'pending', - })) - } - }) + // If the match was in an error state, set it + // to a loading state again. Otherwise, keep it + // as loading or resolved + if (this.state.status === 'idle') { + this.store.setState((s) => ({ + ...s, + status: 'pending', + })) + } const componentsPromise = (async () => { // then run all component and data loaders in parallel @@ -222,11 +264,12 @@ export class RouteMatch< if (this.route.options.onLoad) { return this.route.options.onLoad({ params: this.params, - search: this.state.search, + routeSearch, + search, signal: this.abortController.signal, preload: !!opts?.preload, - routeContext: this.routeContext, - context: this.context, + routeContext: routeContext, + context: context, }) } return @@ -256,4 +299,6 @@ export class RouteMatch< return this.__loadPromise } + + #latestId = '' } diff --git a/packages/router/src/router.ts b/packages/router/src/router.ts index 773b0ce598..76f1454b4f 100644 --- a/packages/router/src/router.ts +++ b/packages/router/src/router.ts @@ -447,6 +447,7 @@ export class Router< try { await this.loadMatches( matches, + this.state.pendingLocation!, // opts ) } catch (err: any) { @@ -511,6 +512,8 @@ export class Router< }) }) + const prevLocation = this.state.currentLocation + this.store.setState((s) => ({ ...s, status: 'idle', @@ -520,7 +523,13 @@ export class Router< pendingMatches: undefined, })) - this.options.onRouteChange?.() + matches.forEach((match) => { + match.__commit() + }) + + if (prevLocation!.href !== this.state.currentLocation.href) { + this.options.onRouteChange?.() + } this.resolveNavigation() } @@ -542,7 +551,7 @@ export class Router< const matches = this.matchRoutes(next.pathname, { strictParseParams: true, }) - await this.loadMatches(matches) + await this.loadMatches(matches, next) return matches } @@ -554,7 +563,7 @@ export class Router< strictParseParams: true, }) - await this.loadMatches(matches, { + await this.loadMatches(matches, next, { preload: true, }) return matches @@ -666,13 +675,12 @@ export class Router< loadMatches = async ( resolvedMatches: RouteMatch[], + location: ParsedLocation, opts?: { preload?: boolean // filter?: (match: RouteMatch) => any }, ) => { - initMatches(resolvedMatches) - // Check each match middleware to see if the route can be accessed await Promise.all( resolvedMatches.map(async (match) => { @@ -692,22 +700,14 @@ export class Router< ) const matchPromises = resolvedMatches.map(async (match, index) => { - const prevMatch = resolvedMatches[(index = 1)] - const search = match.state.search as { __data?: any } + const parentMatch = resolvedMatches[index - 1] - // if (opts?.filter && !opts.filter(match)) { - // return - // } + match.__load({ preload: opts?.preload, location, parentMatch }) - match.load({ preload: opts?.preload }) + await match.__loadPromise - if (match.state.status !== 'success' && match.__loadPromise) { - // Wait for the first sign of activity from the match - await match.__loadPromise - } - - if (prevMatch) { - await prevMatch.__loadPromise + if (parentMatch) { + await parentMatch.__loadPromise } }) @@ -800,11 +800,6 @@ export class Router< } if (opts?.includeSearch ?? true) { - console.log( - baseLocation.search, - next.search, - partialDeepEqual(baseLocation.search, next.search), - ) return partialDeepEqual(baseLocation.search, next.search) ? match : false } @@ -824,8 +819,6 @@ export class Router< replace, activeOptions, preload, - preloadMaxAge: userPreloadMaxAge, - preloadGcMaxAge: userPreloadGcMaxAge, preloadDelay: userPreloadDelay, disabled, }: LinkOptions): LinkInfo => { @@ -985,8 +978,6 @@ export class Router< })) }) - initMatches(currentMatches) - return { ...s, ...dehydratedRouter.state, @@ -1185,10 +1176,3 @@ function getInitialRouterState(): RouterStore { function isCtrlEvent(e: MouseEvent) { return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) } - -function initMatches(matches: RouteMatch[]) { - matches.forEach((match, index) => { - const parentMatch = matches[index - 1] - match.__init({ parentMatch }) - }) -}