From 6cd69b11dc3cedc3ec1e481f1404bd2ce9a64d11 Mon Sep 17 00:00:00 2001
From: joonhoekim <26rote@gmail.com>
Date: Fri, 3 Oct 2025 15:20:42 +0900
Subject: (김준회) spreadjs 렌더링 사이클 오류 수정: avilableTemplates 변경시
 selectedTemplateId 변경하도록 처리
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 components/form-data/spreadJS-dialog.tsx | 30 +++++++++++++++++++-----------
 1 file changed, 19 insertions(+), 11 deletions(-)

(limited to 'components/form-data/spreadJS-dialog.tsx')

diff --git a/components/form-data/spreadJS-dialog.tsx b/components/form-data/spreadJS-dialog.tsx
index 8243566a..1249ebd5 100644
--- a/components/form-data/spreadJS-dialog.tsx
+++ b/components/form-data/spreadJS-dialog.tsx
@@ -299,19 +299,27 @@ export function TemplateViewDialog({
       TYPE: t.TMPL_TYPE
     })));
 
-    if (validTemplates.length > 0 && !selectedTemplateId) {
-      const firstTemplate = validTemplates[0];
-      // 🔍 TMPL_ID 검증 (isValidTemplate로 필터링했으므로 존재해야 하지만 안전장치)
-      if (firstTemplate?.TMPL_ID) {
-        const templateTypeToSet = determineTemplateType(firstTemplate);
-        console.log(`🎯 Auto-selecting first template: ${firstTemplate.TMPL_ID} (${templateTypeToSet})`);
-        setSelectedTemplateId(firstTemplate.TMPL_ID);
-        setTemplateType(templateTypeToSet);
+    if (validTemplates.length > 0) {
+      // 🔍 현재 선택된 템플릿이 availableTemplates에 있는지 확인
+      const selectedExists = selectedTemplateId && validTemplates.some(t => t.TMPL_ID === selectedTemplateId);
+      
+      if (!selectedExists) {
+        // 선택된 템플릿이 없거나 유효하지 않으면 첫 번째 템플릿 선택
+        const firstTemplate = validTemplates[0];
+        if (firstTemplate?.TMPL_ID) {
+          const templateTypeToSet = determineTemplateType(firstTemplate);
+          console.log(`🎯 ${selectedTemplateId ? 'Re-selecting' : 'Auto-selecting'} first template: ${firstTemplate.TMPL_ID} (${templateTypeToSet})`);
+          if (selectedTemplateId) {
+            console.warn(`⚠️ Previously selected "${selectedTemplateId}" not found in availableTemplates, switching to "${firstTemplate.TMPL_ID}"`);
+          }
+          setSelectedTemplateId(firstTemplate.TMPL_ID);
+          setTemplateType(templateTypeToSet);
+        } else {
+          console.error('❌ First valid template has no TMPL_ID:', firstTemplate);
+        }
       } else {
-        console.error('❌ First valid template has no TMPL_ID:', firstTemplate);
+        console.log(`✅ Template already selected and valid: ${selectedTemplateId}`);
       }
-    } else if (selectedTemplateId) {
-      console.log(`ℹ️ Template already selected: ${selectedTemplateId}`);
     }
   }, [templateData, selectedTemplateId, isValidTemplate, determineTemplateType, columnsJSON]);
 
-- 
cgit v1.2.3

