Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

use event listener on vite:preloadError to handle the issue globally

ThieryMichel9b4b08a51e37
diff --git a/registry.json b/registry.json
index 25abfda5..7b98a23d 100644
--- a/registry.json
+++ b/registry.json
@@ -864,10 +864,6 @@
{
"path": "src/lib/toSlug.ts",
"type": "registry:lib"
- },
- {
- "path": "src/lib/lazyImportWithReload.ts",
- "type": "registry:lib"
}
]
}
diff --git a/src/components/atomic-crm/deals/index.ts b/src/components/atomic-crm/deals/index.ts
index d220b60e..292005c3 100644
--- a/src/components/atomic-crm/deals/index.ts
+++ b/src/components/atomic-crm/deals/index.ts
@@ -1,6 +1,6 @@
-import { lazyImportWithReload } from "@/lib/lazyImportWithReload";
+import React from "react";
-const DealList = lazyImportWithReload(() => import("./DealList"), "DealList");
+const DealList = React.lazy(() => import("./DealList"));
export default {
list: DealList,
diff --git a/src/lib/lazyImportWithReload.ts b/src/lib/lazyImportWithReload.ts
deleted file mode 100644
index 61cc9e98..00000000
--- a/src/lib/lazyImportWithReload.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import React from "react";
-
-/**
- * Lazy-load with a full page reload on chunk load failure.
- * After a new deploy, the old service worker pre-cache may be replaced
- * while the page still holds old chunk references. A reload picks up
- * the new HTML + new SW cache, resolving the mismatch.
- * A sessionStorage guard prevents infinite reload loops.
- * Fow when we are offline with no cached version, the error is surfaced as usual.
- */
-export function lazyImportWithReload<T extends React.ComponentType<unknown>>(
- importFn: () => Promise<{ default: T }>,
- chunkName: string,
-) {
- return React.lazy(() =>
- importFn().catch(() => {
- const key = `chunk-reload:${chunkName}`;
- if (!sessionStorage.getItem(key)) {
- sessionStorage.setItem(key, "1");
- window.location.reload();
- }
- // If we already reloaded once this session, surface the error
- return Promise.reject(
- new Error(`Failed to load chunk "${chunkName}" after reload`),
- );
- }),
- );
-}
diff --git a/src/main.tsx b/src/main.tsx
index eff7ccc6..c8f4df3f 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -3,6 +3,18 @@ import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.tsx";
+// After a new deploy, the service worker may replace its pre-cache while
+// the page still holds old chunk references. A reload picks up the new
+// HTML + new SW cache. A sessionStorage guard prevents infinite loops.
+// See https://vite.dev/guide/build.html#load-error-handling
+window.addEventListener("vite:preloadError", () => {
+ const key = "chunk-reload";
+ if (!sessionStorage.getItem(key)) {
+ sessionStorage.setItem(key, "1");
+ window.location.reload();
+ }
+});
+
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />