Repository navigation
fix(router): do not reload for a chunk cancelled while the page unloads #8830
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
Open
theRizwan
wants to merge
3
commits into
TanStack:main
Choose a base branch
from
theRizwan:fix/lazy-chunk-reload-during-unload
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+698
−19
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
936a107
fix(router): do not reload for a chunk cancelled while the page unloads
theRizwan d2f183e
fix(router): listen for the page staying as soon as an unload cancels…
theRizwan 1b76a4a
fix(router): treat imports started after beforeunload as cancelled by…
theRizwan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| --- | ||
| '@tanstack/router-core': patch | ||
| '@tanstack/react-router': patch | ||
| '@tanstack/solid-router': patch | ||
| '@tanstack/vue-router': patch | ||
| --- | ||
|
|
||
| Do not reload the page when Firefox or Safari cancel a pending route chunk because the user is leaving the page. The cancellation has the same message as a missing chunk, and the stale-deploy reload replaced the user's navigation. If the page stays after all, the chunk import is retried. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
188 changes: 188 additions & 0 deletions
188
packages/react-router/tests/lazy-route-chunk-unload.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| import * as React from 'react' | ||
| import { cleanup, fireEvent, render, screen } from '@testing-library/react' | ||
| import { afterEach, expect, test, vi } from 'vitest' | ||
| import { createControlledPromise } from '@tanstack/router-core' | ||
| import { lazyRouteComponent } from '../src' | ||
|
|
||
| // https://github.com/TanStack/router/issues/8827 | ||
| const message = | ||
| 'error loading dynamically imported module: http://localhost/assets/page.js' | ||
| const reloadKey = `tanstack_router_reload:${message}` | ||
|
|
||
| afterEach(() => { | ||
| cleanup() | ||
| // Clears the shared state left by a test that ends while the page is leaving. | ||
| window.dispatchEvent(new Event('pageshow')) | ||
| sessionStorage.clear() | ||
| vi.restoreAllMocks() | ||
| }) | ||
|
|
||
| // jsdom cannot reload, so React retries the render and reaches the error that | ||
| // the reload guard rethrows once its key is set. | ||
| class ErrorBoundary extends React.Component< | ||
| { children: React.ReactNode }, | ||
| { error: unknown } | ||
| > { | ||
| state: { error: unknown } = { error: undefined } | ||
| static getDerivedStateFromError(error: unknown) { | ||
| return { error } | ||
| } | ||
| render() { | ||
| return this.state.error ? <div>Error</div> : this.props.children | ||
| } | ||
| } | ||
|
|
||
| function renderLazy(Page: ReturnType<typeof lazyRouteComponent>) { | ||
| return render( | ||
| <ErrorBoundary> | ||
| <React.Suspense fallback={<div>Loading</div>}> | ||
| <Page /> | ||
| </React.Suspense> | ||
| </ErrorBoundary>, | ||
| ) | ||
| } | ||
|
|
||
| test('does not reload when the import is cancelled because the page is unloading', async () => { | ||
| vi.spyOn(console, 'error').mockImplementation(() => {}) | ||
| const first = createControlledPromise<never>() | ||
| const importer = vi | ||
| .fn() | ||
| .mockReturnValueOnce(first) | ||
| .mockResolvedValueOnce({ default: () => <div>Loaded</div> }) | ||
| const Page = lazyRouteComponent(importer) | ||
|
|
||
| const preload = Page.preload!() | ||
| window.dispatchEvent(new Event('beforeunload')) | ||
| first.reject(new TypeError(message)) | ||
| await preload | ||
|
|
||
| renderLazy(Page) | ||
| expect(screen.getByText('Loading')).toBeInTheDocument() | ||
| expect(sessionStorage.getItem(reloadKey)).toBeNull() | ||
|
|
||
| // The page stayed after all, so the import is retried. | ||
| fireEvent.pointerDown(document.body) | ||
| expect(await screen.findByText('Loaded')).toBeInTheDocument() | ||
| expect(importer).toHaveBeenCalledTimes(2) | ||
| expect(sessionStorage.getItem(reloadKey)).toBeNull() | ||
| }) | ||
|
|
||
| test('reloads once if the retried import is still missing after the page stays', async () => { | ||
| vi.spyOn(console, 'error').mockImplementation(() => {}) | ||
| const first = createControlledPromise<never>() | ||
| const importer = vi | ||
| .fn() | ||
| .mockReturnValueOnce(first) | ||
| .mockRejectedValueOnce(new TypeError(message)) | ||
| const Page = lazyRouteComponent(importer) | ||
|
|
||
| const preload = Page.preload!() | ||
| window.dispatchEvent(new Event('beforeunload')) | ||
| first.reject(new TypeError(message)) | ||
| await preload | ||
|
|
||
| renderLazy(Page) | ||
| fireEvent.keyDown(document.body) | ||
| await vi.waitFor(() => expect(sessionStorage.getItem(reloadKey)).toBe('1')) | ||
| expect(importer).toHaveBeenCalledTimes(2) | ||
| }) | ||
|
|
||
| test('still reloads once for a missing module when the page is not unloading', async () => { | ||
| vi.spyOn(console, 'error').mockImplementation(() => {}) | ||
| const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message))) | ||
|
|
||
| await Page.preload!() | ||
| renderLazy(Page) | ||
|
|
||
| expect(sessionStorage.getItem(reloadKey)).toBe('1') | ||
| }) | ||
|
|
||
| test('stops watching for unload once the import settles', async () => { | ||
| vi.spyOn(console, 'error').mockImplementation(() => {}) | ||
| const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message))) | ||
|
|
||
| await Page.preload!() | ||
| // A later unload must not be attributed to the import that already failed. | ||
| window.dispatchEvent(new Event('beforeunload')) | ||
| renderLazy(Page) | ||
|
|
||
| expect(sessionStorage.getItem(reloadKey)).toBe('1') | ||
| }) | ||
|
|
||
| test('retries when the page stays before the route renders', async () => { | ||
| vi.spyOn(console, 'error').mockImplementation(() => {}) | ||
| const first = createControlledPromise<never>() | ||
| const importer = vi | ||
| .fn() | ||
| .mockReturnValueOnce(first) | ||
| .mockResolvedValueOnce({ default: () => <div>Loaded</div> }) | ||
| const Page = lazyRouteComponent(importer) | ||
|
|
||
| const preload = Page.preload!() | ||
| window.dispatchEvent(new Event('beforeunload')) | ||
| first.reject(new TypeError(message)) | ||
| await preload | ||
|
|
||
| // Restored from the back/forward cache before the route is rendered. | ||
| window.dispatchEvent(new Event('pageshow')) | ||
| await Promise.resolve() | ||
|
|
||
| renderLazy(Page) | ||
| expect(await screen.findByText('Loaded')).toBeInTheDocument() | ||
| expect(importer).toHaveBeenCalledTimes(2) | ||
| expect(sessionStorage.getItem(reloadKey)).toBeNull() | ||
| }) | ||
|
|
||
| test('does not reload for an import that starts after the page began unloading', async () => { | ||
| vi.spyOn(console, 'error').mockImplementation(() => {}) | ||
| const pending = createControlledPromise<never>() | ||
| const late = createControlledPromise<never>() | ||
| const Other = lazyRouteComponent(() => pending) | ||
| const importer = vi | ||
| .fn() | ||
| .mockReturnValueOnce(late) | ||
| .mockResolvedValueOnce({ default: () => <div>Loaded</div> }) | ||
| const Page = lazyRouteComponent(importer) | ||
|
|
||
| // Another route is still loading when the user leaves. | ||
| void Other.preload!() | ||
| window.dispatchEvent(new Event('beforeunload')) | ||
|
|
||
| // This import starts after beforeunload and is cancelled by the unload. | ||
| const preload = Page.preload!() | ||
| late.reject(new TypeError(message)) | ||
| await preload | ||
|
|
||
| renderLazy(Page) | ||
| expect(sessionStorage.getItem(reloadKey)).toBeNull() | ||
|
|
||
| fireEvent.pointerDown(document.body) | ||
| expect(await screen.findByText('Loaded')).toBeInTheDocument() | ||
| expect(importer).toHaveBeenCalledTimes(2) | ||
| expect(sessionStorage.getItem(reloadKey)).toBeNull() | ||
| }) | ||
|
|
||
| test('a newer failed preload keeps its error when the page stays', async () => { | ||
| vi.spyOn(console, 'error').mockImplementation(() => {}) | ||
| const first = createControlledPromise<never>() | ||
| const importer = vi | ||
| .fn() | ||
| .mockReturnValueOnce(first) | ||
| .mockRejectedValueOnce(new Error('Broken module')) | ||
| .mockResolvedValueOnce({ default: () => <div>Loaded</div> }) | ||
| const Page = lazyRouteComponent(importer) | ||
|
|
||
| const preload = Page.preload!() | ||
| window.dispatchEvent(new Event('beforeunload')) | ||
| first.reject(new TypeError(message)) | ||
| await preload | ||
|
|
||
| // A second preload fails for another reason before the route renders. | ||
| await Page.preload!() | ||
| window.dispatchEvent(new Event('pageshow')) | ||
| await Promise.resolve() | ||
|
|
||
| renderLazy(Page) | ||
| expect(screen.getByText('Error')).toBeInTheDocument() | ||
| expect(importer).toHaveBeenCalledTimes(2) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A stay event during a pending import does not release the retry wait.
If the page receives a stay event after
beforeunloadand before the import rejects,onStayclears the leaving state, butwatchPageUnload()still returnstrue. The adapters then callwaitForPageToStay()after the rejection. That wait starts new listeners and cannot observe the earlier stay. The retry therefore waits for anotherpageshow,pointerdown, orkeydown. The route can remain pending until the user interacts again.The retry must run once the page has stayed, whichever event came first. Arm the stay observation before the import can reject, or record the stay so that the post-rejection wait resolves immediately. Add a test that dispatches
beforeunload, dispatches a stay event, rejects the import with the cancellation message, and expects the retry without another event.