Skip to content

Commit 1fb5a56

Browse files
fix(sw): support fixed id value (#1197)
* fix(sw): support fixed id value * refactor * revert --------- Co-authored-by: codesandbox-bot <[email protected]>
1 parent 0ae65cc commit 1fb5a56

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

sandpack-react/src/Playground.stories.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ export const Basic: React.FC = () => {
1414
options={{
1515
showTabs: true,
1616
closableTabs: true,
17+
experimental_enableServiceWorker: true,
18+
experimental_enableStableServiceWorkerId: true,
1719
}}
1820
// customSetup={{
1921
// dependencies: {

sandpack-react/src/contexts/utils/useClient.ts

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -117,9 +117,7 @@ export const useClient: UseClient = (
117117
const debounceHook = useRef<number | undefined>();
118118
const prevEnvironment = useRef(filesState.environment);
119119

120-
const experimental_stableServiceWorkerId = useAsyncSandpackId(
121-
filesState.files
122-
);
120+
const asyncSandpackId = useAsyncSandpackId(filesState.files);
123121

124122
/**
125123
* Callbacks
@@ -159,6 +157,22 @@ export const useClient: UseClient = (
159157
}, timeOut);
160158
}
161159

160+
const getStableServiceWorkerId = async () => {
161+
if (options?.experimental_enableStableServiceWorkerId) {
162+
const key = `SANDPACK_INTERNAL:URL-CONSISTENT-ID`;
163+
let fixedId = localStorage.getItem(key);
164+
165+
if (!fixedId) {
166+
fixedId = await asyncSandpackId();
167+
localStorage.setItem(key, fixedId);
168+
}
169+
170+
return fixedId;
171+
}
172+
173+
return await asyncSandpackId();
174+
};
175+
162176
const client = await loadSandpackClient(
163177
iframe,
164178
{
@@ -180,10 +194,7 @@ export const useClient: UseClient = (
180194
teamId,
181195
experimental_enableServiceWorker:
182196
!!options?.experimental_enableServiceWorker,
183-
experimental_stableServiceWorkerId:
184-
options?.experimental_enableStableServiceWorkerId
185-
? await experimental_stableServiceWorkerId()
186-
: undefined,
197+
experimental_stableServiceWorkerId: await getStableServiceWorkerId(),
187198
sandboxId,
188199
}
189200
);

0 commit comments

Comments
 (0)