Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: retry chunk errors #331

Draft
wants to merge 2 commits into
base: feat/routeprogressbar
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/app/layout/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const SidebarLayout = ({
children,
hideSidebar,
}: {
children: React.ReactNode;
children?: React.ReactNode;
hideSidebar?: boolean;
}) => {
return (
Expand Down
36 changes: 31 additions & 5 deletions src/app/routes/DefaultErrorRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,51 @@
import { NoticeBox } from "@dhis2/ui";
import i18n from "@dhis2/d2-i18n";
import { NoticeBox, Button } from "@dhis2/ui";
import React from "react";
import { useRouteError, isRouteErrorResponse } from "react-router-dom";
import { SidebarLayout } from "../layout";
import { useResetRouter } from "./ResetRouterContext";

const shouldShowResetRoutes = (e) => {
if (e.name === "ChunkLoadError") {
return true;
}
};

export const DefaultErrorRoute = () => {
const error = useRouteError();
const isRouteError = isRouteErrorResponse(error);

let title = "An error occurred";
let message = error?.message ?? "An unknown error occurred.";

if (isRouteError) {
title = error.statusText
message = error?.error?.message
title = error.statusText;
message = error?.error?.message;
}

const showRetry = shouldShowResetRoutes(error);
return (
<SidebarLayout>
<NoticeBox
warning={isRouteError}
error={!isRouteError}
title={title}
>{message}</NoticeBox>
>
{message}
{showRetry && <ResetRoutesRetry />}
</NoticeBox>
</SidebarLayout>
);
};

// A button that can be used to hard reset the routes,
// remounting the router tree.
// This is useful for when a chunk fails to load
const ResetRoutesRetry = () => {
const resetRouter = useResetRouter();

return (
<div style={{ paddingTop: "12px" }}>
<Button onClick={resetRouter}>{i18n.t("Retry")}</Button>
</div>
);
};
7 changes: 7 additions & 0 deletions src/app/routes/ResetRouterContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { createContext, useContext } from "react";

export const ResetRouterContext = createContext<{ reset: () => void }>({
reset: () => ({}),
});

export const useResetRouter = () => useContext(ResetRouterContext).reset;
5 changes: 5 additions & 0 deletions src/app/routes/RetryComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import React from "react";

export function RetryComponent() {
return <div>RetryComponent</div>;
}
86 changes: 36 additions & 50 deletions src/app/routes/Router.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { CircularLoader } from "@dhis2/ui";
import React from "react";
import {
createHashRouter,
Expand All @@ -6,57 +7,18 @@ import {
Navigate,
Route,
createRoutesFromElements,
LazyRouteFunction,
RouteObject,
} from "react-router-dom";
import { SECTIONS_MAP, Section } from "../../constants";
import { Layout } from "../layout";
import { LoadingSpinner } from "../../components/loading";
import { SECTIONS_MAP } from "../../constants";
import { Layout, SidebarLayout } from "../layout";
import { DefaultErrorRoute } from "./DefaultErrorRoute";
import { LegacyAppRedirect } from "./LegacyAppRedirect";
import {
createOverviewLazyRouteFunction,
createSectionLazyRouteFunction,
} from "./lazyLoadFunctions";
import { ResetRouterContext } from "./ResetRouterContext";
import { getSectionPath, routePaths } from "./routePaths";

// This loads all the overview routes in the same chunk since they resolve to the same promise
// see https://reactrouter.com/en/main/route/lazy#multiple-routes-in-a-single-file
// Overviews are small, and the AllOverview would load all the other overviews anyway,
// so it's propbably better to load them all at once
function createOverviewLazyRouteFunction(
componentName: string
): LazyRouteFunction<RouteObject> {
return async () => {
const routeComponent = await import(`../../pages/overview/`);
return {
Component: routeComponent[componentName],
};
};
}

function createSectionLazyRouteFunction(
section: Section,
componentFileName: string
): LazyRouteFunction<RouteObject> {
return async () => {
try {
return await import(
`../../pages/${section.namePlural}/${componentFileName}`
);
} catch (e) {
// means the component is not implemented yet
// fallback to redirect to legacy
if (e.code === "MODULE_NOT_FOUND") {
return {
element: (
<LegacyAppRedirect
section={section}
isNew={componentFileName === "New"}
/>
),
};
}
throw e;
}
};
}

const sectionRoutes = Object.values(SECTIONS_MAP).map((section) => (
<Route
key={section.namePlural}
Expand All @@ -80,7 +42,10 @@ const sectionRoutes = Object.values(SECTIONS_MAP).map((section) => (

const routes = createRoutesFromElements(
<Route element={<Layout />} errorElement={<DefaultErrorRoute />}>
<Route path="/" element={<Navigate to={routePaths.overviewRoot} replace />} />
<Route
path="/"
element={<Navigate to={routePaths.overviewRoot} replace />}
/>
<Route path={routePaths.overviewRoot} element={<Outlet />}>
<Route
index
Expand All @@ -99,8 +64,29 @@ const routes = createRoutesFromElements(
</Route>
);

export const hashRouter = createHashRouter(routes);
const createRouter = (routes: RouteObject[]) => createHashRouter(routes);
const hashRouter = createRouter(routes);

export const ConfiguredRouter = () => {
return <RouterProvider router={hashRouter} />;
const [router, setRouter] = React.useState(hashRouter);

// this can be used to reset the router
// eg when an error occurs, it can be used to retry loading a chunk
// note that this umounts and remounts the entire router-tree
const reset = React.useCallback(() => {
setRouter(createRouter(routes));
}, []);

return (
<ResetRouterContext.Provider value={{ reset }}>
<RouterProvider
router={router}
fallbackElement={
<SidebarLayout>
<LoadingSpinner />
</SidebarLayout>
}
/>
</ResetRouterContext.Provider>
);
};
46 changes: 46 additions & 0 deletions src/app/routes/lazyLoadFunctions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import React from "react";
import { LazyRouteFunction, RouteObject } from "react-router-dom";
import { Section } from "../../constants";
import { LegacyAppRedirect } from "./LegacyAppRedirect";

// This loads all the overview routes in the same chunk since they resolve to the same promise
// see https://reactrouter.com/en/main/route/lazy#multiple-routes-in-a-single-file
// Overviews are small, and the AllOverview would load all the other overviews anyway,
// so it's propbably better to load them all at once
export function createOverviewLazyRouteFunction(
componentName: string
): LazyRouteFunction<RouteObject> {
return async () => {
const routeComponent = await import(`../../pages/overview`);
return {
Component: routeComponent[componentName],
};
};
}

export function createSectionLazyRouteFunction(
section: Section,
componentFileName: string
): LazyRouteFunction<RouteObject> {
return async () => {
// means the component is not implemented yet
// fallback to redirect to legacy
try {
return await import(
`../../pages/${section.namePlural}/${componentFileName}`
);
} catch (e) {
if (e.code === "MODULE_NOT_FOUND") {
return {
element: (
<LegacyAppRedirect
section={section}
isNew={componentFileName === "New"}
/>
),
};
}
throw e;
}
};
}
5 changes: 4 additions & 1 deletion src/components/loading/Loader.module.css
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@

.loadingSpinner {
margin: var(--spacers-dp8);
}

.centered {
margin: var(--spacers-dp8) auto;
}
6 changes: 3 additions & 3 deletions src/components/loading/Loader.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import i18n from "@dhis2/d2-i18n";
import { CircularLoader , NoticeBox } from "@dhis2/ui";
import { CircularLoader, NoticeBox } from "@dhis2/ui";
import React from "react";
import { QueryResponse } from "../../types/query";
import styles from "./Loader.module.css";
import { LoadingSpinner } from "./LoadingSpinner";

interface LoaderProps {
children: React.ReactNode;
Expand All @@ -11,7 +11,7 @@ interface LoaderProps {
}
export const Loader = ({ children, queryResponse, label }: LoaderProps) => {
if (queryResponse.loading) {
return <CircularLoader className={styles.loadingSpinner} />;
return <LoadingSpinner />;
}
if (queryResponse.error) {
const message = queryResponse.error?.message;
Expand Down
10 changes: 10 additions & 0 deletions src/components/loading/LoadingSpinner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { CircularLoader } from "@dhis2/ui";
import cx from "classnames";
import React from "react";
import styles from "./Loader.module.css";

export const LoadingSpinner = ({ centered = true }: { centered?: boolean }) => (
<CircularLoader
className={cx(styles.loadingSpinner, { [styles.centered]: centered })}
/>
);
3 changes: 2 additions & 1 deletion src/components/loading/index.tsx
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { Loader } from './Loader'
export { Loader } from "./Loader";
export { LoadingSpinner } from "./LoadingSpinner";