From 1fb5a56ec1359c09e2e6671a9885368c52f460af Mon Sep 17 00:00:00 2001 From: Danilo Woznica Date: Tue, 10 Sep 2024 11:09:07 +0100 Subject: [PATCH] fix(sw): support fixed id value (#1197) * fix(sw): support fixed id value * refactor * revert --------- Co-authored-by: codesandbox-bot --- sandpack-react/src/Playground.stories.tsx | 2 ++ .../src/contexts/utils/useClient.ts | 25 +++++++++++++------ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/sandpack-react/src/Playground.stories.tsx b/sandpack-react/src/Playground.stories.tsx index c388c902..96aa90ff 100644 --- a/sandpack-react/src/Playground.stories.tsx +++ b/sandpack-react/src/Playground.stories.tsx @@ -14,6 +14,8 @@ export const Basic: React.FC = () => { options={{ showTabs: true, closableTabs: true, + experimental_enableServiceWorker: true, + experimental_enableStableServiceWorkerId: true, }} // customSetup={{ // dependencies: { diff --git a/sandpack-react/src/contexts/utils/useClient.ts b/sandpack-react/src/contexts/utils/useClient.ts index 90828e7a..13c70272 100644 --- a/sandpack-react/src/contexts/utils/useClient.ts +++ b/sandpack-react/src/contexts/utils/useClient.ts @@ -117,9 +117,7 @@ export const useClient: UseClient = ( const debounceHook = useRef(); const prevEnvironment = useRef(filesState.environment); - const experimental_stableServiceWorkerId = useAsyncSandpackId( - filesState.files - ); + const asyncSandpackId = useAsyncSandpackId(filesState.files); /** * Callbacks @@ -159,6 +157,22 @@ export const useClient: UseClient = ( }, timeOut); } + const getStableServiceWorkerId = async () => { + if (options?.experimental_enableStableServiceWorkerId) { + const key = `SANDPACK_INTERNAL:URL-CONSISTENT-ID`; + let fixedId = localStorage.getItem(key); + + if (!fixedId) { + fixedId = await asyncSandpackId(); + localStorage.setItem(key, fixedId); + } + + return fixedId; + } + + return await asyncSandpackId(); + }; + const client = await loadSandpackClient( iframe, { @@ -180,10 +194,7 @@ export const useClient: UseClient = ( teamId, experimental_enableServiceWorker: !!options?.experimental_enableServiceWorker, - experimental_stableServiceWorkerId: - options?.experimental_enableStableServiceWorkerId - ? await experimental_stableServiceWorkerId() - : undefined, + experimental_stableServiceWorkerId: await getStableServiceWorkerId(), sandboxId, } );