Clean up sandpack client lifecycle management

This commit is contained in:
Will Chen
2025-04-12 21:55:00 -07:00
parent 3f782c92de
commit b197ca20f1

View File

@@ -435,7 +435,6 @@ const SandpackIframe = ({ reloadKey }: { reloadKey: number }) => {
const selectedAppId = useAtomValue(selectedAppIdAtom); const selectedAppId = useAtomValue(selectedAppIdAtom);
const { app } = useLoadApp(selectedAppId); const { app } = useLoadApp(selectedAppId);
const keyRef = useRef<number | null>(null); const keyRef = useRef<number | null>(null);
const isFirstRender = useRef(true);
const sandpackClientRef = useRef<SandpackClient | null>(null); const sandpackClientRef = useRef<SandpackClient | null>(null);
async function loadSandpack() { async function loadSandpack() {
@@ -443,9 +442,14 @@ const SandpackIframe = ({ reloadKey }: { reloadKey: number }) => {
keyRef.current = reloadKey; keyRef.current = reloadKey;
if (!selectedAppId) return; if (!selectedAppId) return;
if (sandpackClientRef.current) {
sandpackClientRef.current.destroy();
sandpackClientRef.current = null;
}
const sandboxConfig = await IpcClient.getInstance().getAppSandboxConfig( const sandboxConfig = await IpcClient.getInstance().getAppSandboxConfig(
selectedAppId selectedAppId
); );
if (!iframeRef.current || !app) return; if (!iframeRef.current || !app) return;
const sandpackConfig: SandboxSetup = mapSandpackConfig(sandboxConfig); const sandpackConfig: SandboxSetup = mapSandpackConfig(sandboxConfig);
@@ -487,20 +491,8 @@ const SandpackIframe = ({ reloadKey }: { reloadKey: number }) => {
}, [app]); }, [app]);
useEffect(() => { useEffect(() => {
if (isFirstRender.current) { if (!iframeRef.current || !app || !selectedAppId) return;
isFirstRender.current = false; loadSandpack();
return;
}
if (!iframeRef.current || !app || !selectedAppId) return () => {};
const clientPromise = loadSandpack();
return () => {
clientPromise.then((client) => {
client?.destroy();
sandpackClientRef.current = null;
});
};
}, [reloadKey]); }, [reloadKey]);
const iframeRef = useRef<HTMLIFrameElement>(null); const iframeRef = useRef<HTMLIFrameElement>(null);