Refactor: Improve useEffect hook for sandbox creation

This commit is contained in:
SyedaAnshrahGillani
2025-08-14 13:35:34 +05:00
parent efdef874d7
commit 8b9cd0f939
+23 -9
View File
@@ -136,6 +136,8 @@ export default function AISandboxPage() {
// Clear old conversation data on component mount and create/restore sandbox // Clear old conversation data on component mount and create/restore sandbox
useEffect(() => { useEffect(() => {
let isMounted = true;
const initializePage = async () => { const initializePage = async () => {
// Clear old conversation // Clear old conversation
try { try {
@@ -147,32 +149,44 @@ export default function AISandboxPage() {
console.log('[home] Cleared old conversation data on mount'); console.log('[home] Cleared old conversation data on mount');
} catch (error) { } catch (error) {
console.error('[ai-sandbox] Failed to clear old conversation:', error); console.error('[ai-sandbox] Failed to clear old conversation:', error);
if (isMounted) {
addChatMessage('Failed to clear old conversation data.', 'error');
} }
}
if (!isMounted) return;
// Check if sandbox ID is in URL // Check if sandbox ID is in URL
const sandboxIdParam = searchParams.get('sandbox'); const sandboxIdParam = searchParams.get('sandbox');
if (sandboxIdParam) {
// Try to restore existing sandbox
console.log('[home] Attempting to restore sandbox:', sandboxIdParam);
setLoading(true); setLoading(true);
try { try {
if (sandboxIdParam) {
console.log('[home] Attempting to restore sandbox:', sandboxIdParam);
// For now, just create a new sandbox - you could enhance this to actually restore // For now, just create a new sandbox - you could enhance this to actually restore
// the specific sandbox if your backend supports it // the specific sandbox if your backend supports it
await createSandbox(true); await createSandbox(true);
} catch (error) {
console.error('[ai-sandbox] Failed to restore sandbox:', error);
// Create new sandbox on error
await createSandbox(true);
}
} else { } else {
// Automatically create new sandbox
console.log('[home] No sandbox in URL, creating new sandbox automatically...'); console.log('[home] No sandbox in URL, creating new sandbox automatically...');
await createSandbox(true); await createSandbox(true);
} }
} catch (error) {
console.error('[ai-sandbox] Failed to create or restore sandbox:', error);
if (isMounted) {
addChatMessage('Failed to create or restore sandbox.', 'error');
}
} finally {
if (isMounted) {
setLoading(false);
}
}
}; };
initializePage(); initializePage();
return () => {
isMounted = false;
};
}, []); // Run only on mount }, []); // Run only on mount
useEffect(() => { useEffect(() => {