11import React , {
2+ createContext ,
3+ useCallback ,
24 useEffect ,
35 useRef ,
46 useState ,
@@ -35,6 +37,8 @@ async function fetchServerSideProps(pathname: string) {
3537 throw new Error ( "Failed to fetch" ) ;
3638}
3739
40+ export const ReloadContext = createContext ( async ( ) : Promise < void > => { } ) ;
41+
3842export const RouterHost = ( {
3943 children,
4044 Shell,
@@ -48,37 +52,42 @@ export const RouterHost = ({
4852 ) ;
4953 const [ current , setCurrent ] = useState ( children ) ;
5054 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+ ) ;
5177 useEffect ( ( ) => {
5278 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 ) => {
7380 console . log ( e ) ;
7481 location . href = pathname ;
7582 } ) ;
83+ } else {
84+ // @ts -ignore
85+ delete globalX . __INITIAL_ROUTE__ ;
7686 }
7787 } , [ 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+ ) ;
8291} ;
8392
8493const subscribeToLocationUpdates = ( callback : ( ) => void ) => {
0 commit comments