-
Notifications
You must be signed in to change notification settings - Fork 26.3k
/
redirect-boundary.tsx
70 lines (61 loc) · 1.56 KB
/
redirect-boundary.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
'use client'
import React, { useEffect } from 'react'
import { AppRouterInstance } from '../../shared/lib/app-router-context'
import { useRouter } from './navigation'
import { getURLFromRedirectError, isRedirectError } from './redirect'
interface RedirectBoundaryProps {
router: AppRouterInstance
children: React.ReactNode
}
function HandleRedirect({
redirect,
reset,
}: {
redirect: string
reset: () => void
}) {
const router = useRouter()
useEffect(() => {
// @ts-ignore startTransition exists
React.startTransition(() => {
router.replace(redirect, {})
reset()
})
}, [redirect, reset, router])
return null
}
export class RedirectErrorBoundary extends React.Component<
RedirectBoundaryProps,
{ redirect: string | null }
> {
constructor(props: RedirectBoundaryProps) {
super(props)
this.state = { redirect: null }
}
static getDerivedStateFromError(error: any) {
if (isRedirectError(error)) {
const url = getURLFromRedirectError(error)
return { redirect: url }
}
// Re-throw if error is not for redirect
throw error
}
render() {
const redirect = this.state.redirect
if (redirect !== null) {
return (
<HandleRedirect
redirect={redirect}
reset={() => this.setState({ redirect: null })}
/>
)
}
return this.props.children
}
}
export function RedirectBoundary({ children }: { children: React.ReactNode }) {
const router = useRouter()
return (
<RedirectErrorBoundary router={router}>{children}</RedirectErrorBoundary>
)
}