1
1
import React , {
2
+ createContext ,
3
+ useCallback ,
2
4
useEffect ,
3
5
useRef ,
4
6
useState ,
@@ -35,6 +37,8 @@ async function fetchServerSideProps(pathname: string) {
35
37
throw new Error ( "Failed to fetch" ) ;
36
38
}
37
39
40
+ export const ReloadContext = createContext ( async ( ) : Promise < void > => { } ) ;
41
+
38
42
export const RouterHost = ( {
39
43
children,
40
44
Shell,
@@ -48,37 +52,42 @@ export const RouterHost = ({
48
52
) ;
49
53
const [ current , setCurrent ] = useState ( children ) ;
50
54
const version = useRef < number > ( 0 ) ;
55
+ const reload = useCallback (
56
+ async ( target = location . pathname + location . search ) => {
57
+ if ( typeof target !== "string" ) throw new Error ( "invalid target" , target ) ;
58
+ const currentVersion = ++ version . current ;
59
+ const [ module , props ] = await Promise . all ( [
60
+ import ( match ( target . split ( "?" ) [ 0 ] ) ! . value ) ,
61
+ fetchServerSideProps ( target ) ,
62
+ ] ) ;
63
+ if ( currentVersion === version . current ) {
64
+ if ( props ?. redirect ) {
65
+ navigate ( props . redirect ) ;
66
+ } else {
67
+ setCurrent (
68
+ < Shell { ...props } >
69
+ < module . default { ...props ?. props } />
70
+ </ Shell >
71
+ ) ;
72
+ }
73
+ }
74
+ } ,
75
+ [ ]
76
+ ) ;
51
77
useEffect ( ( ) => {
52
78
if ( pathname !== globalX . __INITIAL_ROUTE__ ) {
53
- ( async ( ) => {
54
- const currentVersion = ++ version . current ;
55
- const [ module , props ] = await Promise . all ( [
56
- import ( match ( pathname . split ( "?" ) [ 0 ] ) ! . value ) ,
57
- fetchServerSideProps ( pathname ) ,
58
- ] ) ;
59
- if ( currentVersion === version . current ) {
60
- if ( props ?. redirect ) {
61
- navigate ( props . redirect ) ;
62
- } else {
63
- // @ts -ignore
64
- delete globalX . __INITIAL_ROUTE__ ;
65
- setCurrent (
66
- < Shell { ...props } >
67
- < module . default { ...props ?. props } />
68
- </ Shell >
69
- ) ;
70
- }
71
- }
72
- } ) ( ) . catch ( ( e ) => {
79
+ reload ( pathname ) . catch ( ( e ) => {
73
80
console . log ( e ) ;
74
81
location . href = pathname ;
75
82
} ) ;
83
+ } else {
84
+ // @ts -ignore
85
+ delete globalX . __INITIAL_ROUTE__ ;
76
86
}
77
87
} , [ pathname ] ) ;
78
- if ( pathname === globalX . __INITIAL_ROUTE__ ) {
79
- return children ;
80
- }
81
- return current ;
88
+ return (
89
+ < ReloadContext . Provider value = { reload } > { current } </ ReloadContext . Provider >
90
+ ) ;
82
91
} ;
83
92
84
93
const subscribeToLocationUpdates = ( callback : ( ) => void ) => {
0 commit comments