Last active
March 22, 2022 14:44
-
-
Save ozkary/92e587c18468f5ed4d815606304f6752 to your computer and use it in GitHub Desktop.
Route loader when using lazy loading and dynamic imports to manage ChunkLoadErrors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @file routes/routeLoader.ts | |
| * @description lazy loading of routes. | |
| * | |
| * @author ogarcia (ozkary) | |
| * | |
| */ | |
| /** | |
| * Use this route loader when using lazy loading and dynamic imports | |
| * @param factory function for dynamic load of routes | |
| * @param maxRetry number of retries | |
| * @returns a page container | |
| */ | |
| const routeLoader = <T>(factory: () => Promise<T>, maxRetry = 3): Promise<T> => { | |
| return new Promise((resolve, reject) => { | |
| factory() | |
| .then(resolve) | |
| .catch((error) => { | |
| if (maxRetry === 0) { | |
| reject(error); | |
| // this is probably a white page error. reload the main page | |
| // alt - add better messaging or load another page | |
| window.location.reload(); | |
| return; | |
| } | |
| // recursively try again reducing the retry count | |
| routeLoader(factory, --maxRetry).then(resolve, reject); | |
| }); | |
| }); | |
| }; | |
| export default routeLoader; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @file routes/index.ts | |
| * @description application router | |
| * | |
| * @author ogarcia (ozkary) | |
| * | |
| */ | |
| import React, { lazy } from 'react'; | |
| import { Switch, Route } from 'react-router-dom'; | |
| import routeLoader from '../../routes/routeLoader'; | |
| // define the app routes with component association | |
| const routes = [ | |
| { | |
| path: ['/home'], | |
| component: '/Home' | |
| }, | |
| { | |
| path: ['/login'], | |
| component: '/Customer' | |
| }, | |
| { | |
| path: ['/profile'], | |
| component: '/Payment' | |
| } | |
| ]; | |
| /** | |
| * simple router component to manage the app routes | |
| * | |
| */ | |
| const Router = (): JSX.Element => { | |
| return ( | |
| <Switch> | |
| {routes.map((route) => { | |
| return ( | |
| <Route | |
| key={route.component} | |
| path={route.path} | |
| exact={true} | |
| component={lazy(() => | |
| routeLoader(() => import(`../containers/${route.component}`)) | |
| )} | |
| /> | |
| ); | |
| })} | |
| </Switch> | |
| ); | |
| }; | |
| export default Router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment