-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathClientRouter.tsx
More file actions
72 lines (67 loc) · 2.32 KB
/
ClientRouter.tsx
File metadata and controls
72 lines (67 loc) · 2.32 KB
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
71
72
import React, { useEffect } from 'react';
import { RouterProvider } from 'react-router-dom';
import { createRouter } from '@remix-run/router';
import type { To, History, Router } from '@remix-run/router';
import type { ClientAppRouterProps } from './types.js';
import App from './App.js';
import { useAppContext } from './AppContext.js';
import { setHistory } from './history.js';
import { disableHistoryWarning } from './utils/deprecatedHistory.js';
function createRouterHistory(history: History, router: Router) {
const routerHistory = history;
routerHistory.push = (to: To, state) => {
router.navigate(to, { replace: false, state });
};
routerHistory.replace = (to: To, state) => {
router.navigate(to, { replace: true, state });
};
routerHistory.go = (delta: number) => {
router.navigate(delta);
};
return routerHistory;
}
let router: Router = null;
function ClientRouter(props: ClientAppRouterProps) {
const { Component, routerContext } = props;
const { revalidate, appConfig } = useAppContext();
function clearRouter() {
if (router) {
router.dispose();
router = null;
}
}
// API createRouter only needs to be called once, and create before mount.
if (process.env.ICE_CORE_ROUTER === 'true') {
// Clear router before re-create in case of hot module replacement.
clearRouter();
// @ts-expect-error routes type should be AgnosticBaseRouteObject[]
router = createRouter(routerContext).initialize();
disableHistoryWarning();
// Replace history methods by router navigate for backwards compatibility.
setHistory(createRouterHistory({ ...routerContext.history }, router));
}
useEffect(() => {
if (revalidate) {
// Revalidate after render for SSG while staticDataLoader and dataLoader both defined.
router?.revalidate();
}
return () => {
// In case of micro app, ClientRouter will be unmounted,
// duspose router before mount again.
clearRouter();
};
}, [revalidate]);
let element: React.ReactNode;
if (process.env.ICE_CORE_ROUTER === 'true') {
const fallbackElement = appConfig?.router?.fallbackElement ?? null;
element = <RouterProvider router={router} fallbackElement={fallbackElement} />;
} else {
element = <Component />;
}
return (
<App>
{element}
</App>
);
}
export default ClientRouter;