Created
October 15, 2020 23:02
-
-
Save atdrago/7004086769c2a695b47524280660fffa to your computer and use it in GitHub Desktop.
Reload page when ChunkLoadError occurs
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
| import { lazy } from 'react'; | |
| /** | |
| * Uses React's `lazy` utility underneath, and works the same way, but | |
| * `lazyRoute` will handle the "ChunkLoadError" error by reloading the page. | |
| * This is generally a good solution when the user runs into a "ChunkLoadError" | |
| * while changing routes. All other errors will be passed along as normal. | |
| * @param factory The function that returns the result of webpack's `import` | |
| * @example | |
| * const Page = lazyRoute(() => import('components/pages/Page')); | |
| * | |
| * <Route> | |
| * <Page /> | |
| * </Route> | |
| */ | |
| export function lazyRoute<TComponentType extends React.ComponentType<any>>( | |
| factory: () => Promise<{ | |
| default: TComponentType; | |
| }>, | |
| ) { | |
| return lazy( | |
| () => | |
| new Promise<{ default: TComponentType }>((resolve, reject) => { | |
| factory() | |
| .then((result) => resolve(result)) | |
| .catch((err) => { | |
| if (err.name === 'ChunkLoadError') { | |
| // Handle ChunkLoadErrors by reloading the page. Do not reject in | |
| // this situation to prevent the user from seeing an error | |
| window.location.reload(); | |
| } else { | |
| reject(err); | |
| } | |
| }); | |
| }), | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment