Unverified Commit babe5036 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Reset not-found and error boundary when navigating (#49855)

## What?

Currently the error boundary state does not reset when a navigation
happens because the `key` does not change. Because of that navigating
using next/link when the error boundary is in the open state ends up not
rendering the contents of the new navigation, instead it keeps the error
boundary contents.

## How?

This PR uses a pattern that is recommended in the React docs (setState
during render) to reset the error boundary if the `usePathname` value
has changed, it is used as a proxy for a new navigation.

Fixes #47862
Fixes NEXT-963
Fixes #49736
Fixes #49732
Fixes #49599


<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation or adding/fixing Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md



## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent e5eab8b3
'use client' 'use client'
import React from 'react' import React from 'react'
import { usePathname } from './navigation'
const styles = { const styles = {
error: { error: {
...@@ -36,19 +37,50 @@ export interface ErrorBoundaryProps { ...@@ -36,19 +37,50 @@ export interface ErrorBoundaryProps {
errorStyles?: React.ReactNode | undefined errorStyles?: React.ReactNode | undefined
} }
interface ErrorBoundaryHandlerProps extends ErrorBoundaryProps {
pathname: string
}
interface ErrorBoundaryHandlerState {
error: Error | null
previousPathname: string
}
export class ErrorBoundaryHandler extends React.Component< export class ErrorBoundaryHandler extends React.Component<
ErrorBoundaryProps, ErrorBoundaryHandlerProps,
{ error: Error | null } ErrorBoundaryHandlerState
> { > {
constructor(props: ErrorBoundaryProps) { constructor(props: ErrorBoundaryHandlerProps) {
super(props) super(props)
this.state = { error: null } this.state = { error: null, previousPathname: this.props.pathname }
} }
static getDerivedStateFromError(error: Error) { static getDerivedStateFromError(error: Error) {
return { error } return { error }
} }
static getDerivedStateFromProps(
props: ErrorBoundaryHandlerProps,
state: ErrorBoundaryHandlerState
): ErrorBoundaryHandlerState | null {
/**
* Handles reset of the error boundary when a navigation happens.
* Ensures the error boundary does not stay enabled when navigating to a new page.
* Approach of setState in render is safe as it checks the previous pathname and then overrides
* it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders
*/
if (props.pathname !== state.previousPathname && state.error) {
return {
error: null,
previousPathname: props.pathname,
}
}
return {
error: state.error,
previousPathname: props.pathname,
}
}
reset = () => { reset = () => {
this.setState({ error: null }) this.setState({ error: null })
} }
...@@ -105,9 +137,11 @@ export function ErrorBoundary({ ...@@ -105,9 +137,11 @@ export function ErrorBoundary({
errorStyles, errorStyles,
children, children,
}: ErrorBoundaryProps & { children: React.ReactNode }): JSX.Element { }: ErrorBoundaryProps & { children: React.ReactNode }): JSX.Element {
const pathname = usePathname()
if (errorComponent) { if (errorComponent) {
return ( return (
<ErrorBoundaryHandler <ErrorBoundaryHandler
pathname={pathname}
errorComponent={errorComponent} errorComponent={errorComponent}
errorStyles={errorStyles} errorStyles={errorStyles}
> >
......
import React from 'react' import React from 'react'
import { usePathname } from './navigation'
interface NotFoundBoundaryProps { interface NotFoundBoundaryProps {
notFound?: React.ReactNode notFound?: React.ReactNode
...@@ -7,13 +8,25 @@ interface NotFoundBoundaryProps { ...@@ -7,13 +8,25 @@ interface NotFoundBoundaryProps {
children: React.ReactNode children: React.ReactNode
} }
interface NotFoundErrorBoundaryProps extends NotFoundBoundaryProps {
pathname: string
}
interface NotFoundErrorBoundaryState {
notFoundTriggered: boolean
previousPathname: string
}
class NotFoundErrorBoundary extends React.Component< class NotFoundErrorBoundary extends React.Component<
NotFoundBoundaryProps, NotFoundErrorBoundaryProps,
{ notFoundTriggered: boolean } NotFoundErrorBoundaryState
> { > {
constructor(props: NotFoundBoundaryProps) { constructor(props: NotFoundErrorBoundaryProps) {
super(props) super(props)
this.state = { notFoundTriggered: !!props.asNotFound } this.state = {
notFoundTriggered: !!props.asNotFound,
previousPathname: props.pathname,
}
} }
static getDerivedStateFromError(error: any) { static getDerivedStateFromError(error: any) {
...@@ -24,6 +37,28 @@ class NotFoundErrorBoundary extends React.Component< ...@@ -24,6 +37,28 @@ class NotFoundErrorBoundary extends React.Component<
throw error throw error
} }
static getDerivedStateFromProps(
props: NotFoundErrorBoundaryProps,
state: NotFoundErrorBoundaryState
): NotFoundErrorBoundaryState | null {
/**
* Handles reset of the error boundary when a navigation happens.
* Ensures the error boundary does not stay enabled when navigating to a new page.
* Approach of setState in render is safe as it checks the previous pathname and then overrides
* it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders
*/
if (props.pathname !== state.previousPathname && state.notFoundTriggered) {
return {
notFoundTriggered: false,
previousPathname: props.pathname,
}
}
return {
notFoundTriggered: state.notFoundTriggered,
previousPathname: props.pathname,
}
}
render() { render() {
if (this.state.notFoundTriggered) { if (this.state.notFoundTriggered) {
return ( return (
...@@ -45,8 +80,10 @@ export function NotFoundBoundary({ ...@@ -45,8 +80,10 @@ export function NotFoundBoundary({
asNotFound, asNotFound,
children, children,
}: NotFoundBoundaryProps) { }: NotFoundBoundaryProps) {
const pathname = usePathname()
return notFound ? ( return notFound ? (
<NotFoundErrorBoundary <NotFoundErrorBoundary
pathname={pathname}
notFound={notFound} notFound={notFound}
notFoundStyles={notFoundStyles} notFoundStyles={notFoundStyles}
asNotFound={asNotFound} asNotFound={asNotFound}
......
'use client'
import Link from 'next/link'
export default function ErrorComponent() {
return (
<>
<h1 id="error-component">Error Happened!</h1>
<Link href="/result" id="to-result">
To Result
</Link>
</>
)
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function NotFound() {
return (
<>
<h1 id="not-found-component">Not Found!</h1>
<Link href="/result" id="to-result">
To Result
</Link>
</>
)
}
export default function Page() {
return <h1 id="homepage">Home</h1>
}
export default function Page() {
return <h1 id="result-page">Result Page!</h1>
}
import { notFound } from 'next/navigation'
export const dynamic = 'force-dynamic'
export default function Page() {
notFound()
}
export const dynamic = 'force-dynamic'
export default function Page() {
throw new Error('This is an error')
}
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'not-found-linking',
{
files: __dirname,
},
({ next }) => {
it('should allow navigation on not-found', async () => {
const browser = await next.browser('/trigger-404')
expect(await browser.elementByCss('#not-found-component').text()).toBe(
'Not Found!'
)
expect(
await browser
.elementByCss('#to-result')
.click()
.waitForElementByCss('#result-page')
.text()
).toBe('Result Page!')
})
it('should allow navigation on error', async () => {
const browser = await next.browser('/trigger-error')
expect(await browser.elementByCss('#error-component').text()).toBe(
'Error Happened!'
)
expect(
await browser
.elementByCss('#to-result')
.click()
.waitForElementByCss('#result-page')
.text()
).toBe('Result Page!')
})
}
)
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
typescript: {
ignoreBuildErrors: true,
},
}
module.exports = nextConfig
import Link from 'next/link'
import styles from './style.module.css' import styles from './style.module.css'
export default function NotFound() { export default function NotFound() {
return ( return (
<>
<h1 id="not-found-component" className={styles.red}> <h1 id="not-found-component" className={styles.red}>
Not Found! Not Found!
</h1> </h1>
<Link href="/not-found/result" id="to-result">
To Result
</Link>
</>
) )
} }
export default function Page() {
return <h1 id="result-page">Result Page!</h1>
}
// TODO-APP: enable when flight error serialization is implemented
import { notFound } from 'next/navigation' import { notFound } from 'next/navigation'
export default function Page() { export default function Page() {
......
import { notFound } from 'next/navigation'
export const dynamic = 'force-dynamic'
export default function Page() {
notFound()
return <></>
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment