Open History to see the last commit
1import * as React from 'react'
2import { isNotFound } from '@tanstack/router-core'
3import { isServer } from '@tanstack/router-core/isServer'
4import { useSelector } from '@tanstack/react-store'
5import { CatchBoundary } from './CatchBoundary'
6import { useRouter } from './useRouter'
7import type { ErrorInfo } from 'react'
8import type { NotFoundError } from '@tanstack/router-core'
9β
10export function CatchNotFound(props: {
11 fallback?: (error: NotFoundError) => React.ReactElement
12 onCatch?: (error: NotFoundError, errorInfo: ErrorInfo) => void
13 children: React.ReactNode
14}) {
15 const router = useRouter()
16β
17 if (isServer ?? router.isServer) {
18 const pathname = router.stores.location.get().pathname
19 const status = router.stores.status.get()
20 const resetKey = `not-found-${pathname}-${status}`
21β
22 return (
23 <CatchBoundary
24 getResetKey={() => resetKey}
25 onCatch={(error, errorInfo) => {
26 if (isNotFound(error)) {
27 props.onCatch?.(error, errorInfo)
28 } else {
29 throw error
30 }
31 }}
32 errorComponent={({ error }) => {
33 if (isNotFound(error)) {
34 return props.fallback?.(error)
35 } else {
36 throw error
37 }
38 }}
39 >
40 {props.children}
41 </CatchBoundary>
42 )
43 }
44β
45 // TODO: Some way for the user to programmatically reset the not-found boundary?
46 // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
47 const pathname = useSelector(
48 router.stores.location,
49 (location) => location.pathname,
50 )
51 // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
52 const status = useSelector(router.stores.status)
53 const resetKey = `not-found-${pathname}-${status}`
54β
55 return (
56 <CatchBoundary
57 getResetKey={() => resetKey}
58 onCatch={(error, errorInfo) => {
59 if (isNotFound(error)) {
60 props.onCatch?.(error, errorInfo)
61 } else {
62 throw error
63 }
64 }}
65 errorComponent={({ error }) => {
66 if (isNotFound(error)) {
67 return props.fallback?.(error)
68 } else {
69 throw error
70 }
71 }}
72 >
73 {props.children}
74 </CatchBoundary>
75 )
76}
77β
78export function DefaultGlobalNotFound() {
79 return <p>Not Found</p>
80}