Fix deletion UI freeze
Addresses the issue where the UI becomes unresponsive after deleting a transaction.
This commit is contained in:
@@ -5,7 +5,7 @@ import { toast } from '@/hooks/useToast.wrapper';
|
|||||||
import { handleDeleteStorage } from './deleteTransactionStorage';
|
import { handleDeleteStorage } from './deleteTransactionStorage';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 트랜잭션 삭제 핵심 기능 - 성능 및 안정성 개선
|
* 트랜잭션 삭제 핵심 기능 - 안정성 대폭 개선
|
||||||
*/
|
*/
|
||||||
export const useDeleteTransactionCore = (
|
export const useDeleteTransactionCore = (
|
||||||
transactions: Transaction[],
|
transactions: Transaction[],
|
||||||
@@ -13,9 +13,9 @@ export const useDeleteTransactionCore = (
|
|||||||
user: any,
|
user: any,
|
||||||
pendingDeletionRef: MutableRefObject<Set<string>>
|
pendingDeletionRef: MutableRefObject<Set<string>>
|
||||||
) => {
|
) => {
|
||||||
// 트랜잭션 삭제 - 성능 및 안정성 개선 버전
|
// 트랜잭션 삭제 - 안정성 대폭 개선 버전
|
||||||
return useCallback((id: string): Promise<boolean> => {
|
return useCallback((id: string): Promise<boolean> => {
|
||||||
// 프로미스 생성
|
// 반드시 Promise 반환
|
||||||
return new Promise<boolean>((resolve) => {
|
return new Promise<boolean>((resolve) => {
|
||||||
try {
|
try {
|
||||||
console.log('트랜잭션 삭제 작업 시작 - ID:', id);
|
console.log('트랜잭션 삭제 작업 시작 - ID:', id);
|
||||||
@@ -29,53 +29,88 @@ export const useDeleteTransactionCore = (
|
|||||||
toast({
|
toast({
|
||||||
title: "삭제 실패",
|
title: "삭제 실패",
|
||||||
description: "해당 항목을 찾을 수 없습니다.",
|
description: "해당 항목을 찾을 수 없습니다.",
|
||||||
variant: "destructive"
|
variant: "destructive",
|
||||||
|
duration: 1500
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ID 정리
|
||||||
|
if (pendingDeletionRef.current.has(id)) {
|
||||||
|
pendingDeletionRef.current.delete(id);
|
||||||
|
}
|
||||||
|
|
||||||
resolve(false);
|
resolve(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 즉시 상태 업데이트 (현재 상태에서 삭제할 항목 필터링)
|
|
||||||
const updatedTransactions = transactions.filter(t => t.id !== id);
|
|
||||||
setTransactions(updatedTransactions);
|
|
||||||
|
|
||||||
// 삭제 성공 토스트
|
// 1. UI 업데이트 단계
|
||||||
toast({
|
|
||||||
title: "삭제 완료",
|
|
||||||
description: "지출 항목이 삭제되었습니다.",
|
|
||||||
duration: 1500
|
|
||||||
});
|
|
||||||
|
|
||||||
// 스토리지 업데이트 작업 시작 (백그라운드)
|
|
||||||
try {
|
try {
|
||||||
// 스토리지 처리 (스토리지 및 Supabase 업데이트)
|
// 상태 업데이트 (렌더링 트리거)
|
||||||
handleDeleteStorage(
|
const updatedTransactions = transactions.filter(t => t.id !== id);
|
||||||
updatedTransactions,
|
setTransactions(updatedTransactions);
|
||||||
id,
|
|
||||||
user,
|
|
||||||
pendingDeletionRef
|
|
||||||
);
|
|
||||||
|
|
||||||
// 이벤트 발생
|
// 삭제 성공 토스트 (UI 피드백)
|
||||||
setTimeout(() => {
|
toast({
|
||||||
window.dispatchEvent(new Event('transactionDeleted'));
|
title: "삭제 완료",
|
||||||
}, 100);
|
description: "지출 항목이 삭제되었습니다.",
|
||||||
|
duration: 1500
|
||||||
|
});
|
||||||
|
|
||||||
console.log('삭제 작업 완료:', id);
|
// 2. 스토리지 업데이트 단계 (백그라운드 작업)
|
||||||
resolve(true);
|
try {
|
||||||
} catch (storageError) {
|
// 스토리지 처리 (로컬 스토리지 및 Supabase 업데이트)
|
||||||
console.error('스토리지 작업 오류:', storageError);
|
const storageResult = handleDeleteStorage(
|
||||||
// 스토리지 오류가 발생해도 UI는 이미 업데이트되었으므로 true 반환
|
updatedTransactions,
|
||||||
resolve(true);
|
id,
|
||||||
|
user,
|
||||||
|
pendingDeletionRef
|
||||||
|
);
|
||||||
|
|
||||||
|
// 이벤트 발생
|
||||||
|
setTimeout(() => {
|
||||||
|
window.dispatchEvent(new Event('transactionDeleted'));
|
||||||
|
}, 100);
|
||||||
|
|
||||||
|
console.log('삭제 작업 UI 단계 완료:', id);
|
||||||
|
|
||||||
|
// 스토리지 결과와 관계없이 UI는 이미 업데이트되었으므로 true 반환
|
||||||
|
resolve(true);
|
||||||
|
} catch (storageError) {
|
||||||
|
console.error('스토리지 작업 오류:', storageError);
|
||||||
|
// 스토리지 오류가 발생해도 UI는 이미 업데이트되었으므로 true 반환
|
||||||
|
resolve(true);
|
||||||
|
}
|
||||||
|
} catch (uiError) {
|
||||||
|
console.error('UI 업데이트 단계 오류:', uiError);
|
||||||
|
|
||||||
|
// 중요: 실패해도 pendingDeletion에서 삭제
|
||||||
|
if (pendingDeletionRef.current.has(id)) {
|
||||||
|
pendingDeletionRef.current.delete(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "삭제 실패",
|
||||||
|
description: "지출 항목을 삭제하는 중 오류가 발생했습니다.",
|
||||||
|
variant: "destructive",
|
||||||
|
duration: 1500
|
||||||
|
});
|
||||||
|
|
||||||
|
resolve(false);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('트랜잭션 삭제 오류:', error);
|
console.error('트랜잭션 삭제 전체 오류:', error);
|
||||||
|
|
||||||
|
// 중요: 모든 상황에서 pendingDeletion에서 제거
|
||||||
|
if (pendingDeletionRef.current.has(id)) {
|
||||||
|
pendingDeletionRef.current.delete(id);
|
||||||
|
}
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
title: "삭제 실패",
|
title: "삭제 실패",
|
||||||
description: "지출 삭제 중 오류가 발생했습니다.",
|
description: "지출 삭제 중 오류가 발생했습니다.",
|
||||||
duration: 1500,
|
duration: 1500,
|
||||||
variant: "destructive"
|
variant: "destructive"
|
||||||
});
|
});
|
||||||
|
|
||||||
resolve(false);
|
resolve(false);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,22 +6,35 @@ import { deleteTransactionFromSupabase } from '../../supabaseUtils';
|
|||||||
import { toast } from '@/hooks/useToast.wrapper';
|
import { toast } from '@/hooks/useToast.wrapper';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 스토리지 및 Supabase 삭제 처리 - 간소화 및 안정성 개선
|
* 스토리지 및 Supabase 삭제 처리 - 안정성 대폭 개선
|
||||||
*/
|
*/
|
||||||
export const handleDeleteStorage = (
|
export const handleDeleteStorage = (
|
||||||
updatedTransactions: Transaction[],
|
updatedTransactions: Transaction[],
|
||||||
id: string,
|
id: string,
|
||||||
user: any,
|
user: any,
|
||||||
pendingDeletionRef: MutableRefObject<Set<string>>
|
pendingDeletionRef: MutableRefObject<Set<string>>
|
||||||
) => {
|
): boolean => {
|
||||||
try {
|
try {
|
||||||
// 로컬 스토리지 업데이트
|
// 로컬 스토리지 업데이트 (동기 처리)
|
||||||
saveTransactionsToStorage(updatedTransactions);
|
try {
|
||||||
console.log('로컬 스토리지 저장 완료');
|
saveTransactionsToStorage(updatedTransactions);
|
||||||
|
console.log('로컬 스토리지 저장 완료');
|
||||||
|
} catch (storageError) {
|
||||||
|
console.error('로컬 스토리지 저장 실패:', storageError);
|
||||||
|
// 스토리지 실패해도 계속 진행 (Supabase 업데이트 시도)
|
||||||
|
}
|
||||||
|
|
||||||
// Supabase 업데이트 (비동기 처리)
|
// Supabase 업데이트 (비동기 처리)
|
||||||
if (user) {
|
if (user) {
|
||||||
// 네트워크 작업은 비동기로 진행 - 실패해도 UI에 영향 없음
|
// 네트워크 작업은 비동기로 진행 - 실패해도 UI에 영향 없음
|
||||||
|
// 타임아웃 설정 (10초)
|
||||||
|
const timeoutId = setTimeout(() => {
|
||||||
|
console.warn('Supabase 삭제 작업 시간 초과:', id);
|
||||||
|
if (pendingDeletionRef.current) {
|
||||||
|
pendingDeletionRef.current.delete(id);
|
||||||
|
}
|
||||||
|
}, 10000);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
deleteTransactionFromSupabase(user, id)
|
deleteTransactionFromSupabase(user, id)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
@@ -31,6 +44,9 @@ export const handleDeleteStorage = (
|
|||||||
console.error('Supabase 삭제 오류:', error);
|
console.error('Supabase 삭제 오류:', error);
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
|
// 타임아웃 취소
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
|
||||||
// 작업 완료 후 반드시 pendingDeletion에서 제거
|
// 작업 완료 후 반드시 pendingDeletion에서 제거
|
||||||
if (pendingDeletionRef.current) {
|
if (pendingDeletionRef.current) {
|
||||||
pendingDeletionRef.current.delete(id);
|
pendingDeletionRef.current.delete(id);
|
||||||
@@ -38,6 +54,9 @@ export const handleDeleteStorage = (
|
|||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Supabase 작업 오류:', e);
|
console.error('Supabase 작업 오류:', e);
|
||||||
|
// 타임아웃 취소
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
|
||||||
// 작업 완료 표시
|
// 작업 완료 표시
|
||||||
if (pendingDeletionRef.current) {
|
if (pendingDeletionRef.current) {
|
||||||
pendingDeletionRef.current.delete(id);
|
pendingDeletionRef.current.delete(id);
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { useDeleteTransactionCore } from './deleteOperation/deleteTransactionCor
|
|||||||
import { toast } from '@/hooks/useToast.wrapper';
|
import { toast } from '@/hooks/useToast.wrapper';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 트랜잭션 삭제 기능 - 성능 및 안정성 개선
|
* 트랜잭션 삭제 기능 - 안정성 대폭 개선
|
||||||
*/
|
*/
|
||||||
export const useDeleteTransaction = (
|
export const useDeleteTransaction = (
|
||||||
transactions: Transaction[],
|
transactions: Transaction[],
|
||||||
@@ -16,8 +16,11 @@ export const useDeleteTransaction = (
|
|||||||
const pendingDeletionRef = useRef<Set<string>>(new Set());
|
const pendingDeletionRef = useRef<Set<string>>(new Set());
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
|
|
||||||
// 삭제 작업 타임아웃 관리를 위한 ref
|
// 삭제 작업 타임아웃 관리를 위한 ref (ID별로 관리)
|
||||||
const timeoutRef = useRef<Record<string, NodeJS.Timeout>>({});
|
const timeoutRef = useRef<Record<string, NodeJS.Timeout>>({});
|
||||||
|
|
||||||
|
// 삭제 완료 이벤트 추적을 위한 ref
|
||||||
|
const deleteCompletedRef = useRef<boolean>(false);
|
||||||
|
|
||||||
// 핵심 삭제 로직 사용
|
// 핵심 삭제 로직 사용
|
||||||
const deleteTransactionHandler = useDeleteTransactionCore(
|
const deleteTransactionHandler = useDeleteTransactionCore(
|
||||||
@@ -27,9 +30,24 @@ export const useDeleteTransaction = (
|
|||||||
pendingDeletionRef
|
pendingDeletionRef
|
||||||
);
|
);
|
||||||
|
|
||||||
// 성능 및 안정성 개선 버전
|
// 모든 타임아웃 정리 유틸리티 함수
|
||||||
|
const clearAllTimeouts = useCallback(() => {
|
||||||
|
Object.values(timeoutRef.current).forEach(timeout => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
});
|
||||||
|
timeoutRef.current = {};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 안전장치: 등록된 모든 pendingDeletion ID 정리
|
||||||
|
const clearAllPendingDeletions = useCallback(() => {
|
||||||
|
pendingDeletionRef.current.clear();
|
||||||
|
deleteCompletedRef.current = true;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 완전히 개선된 삭제 함수 - 안정성 및 에러 처리 강화
|
||||||
const deleteTransaction = useCallback(async (id: string): Promise<boolean> => {
|
const deleteTransaction = useCallback(async (id: string): Promise<boolean> => {
|
||||||
console.log('트랜잭션 삭제 시작:', id);
|
console.log('트랜잭션 삭제 요청:', id, '현재 처리 중인 항목:',
|
||||||
|
Array.from(pendingDeletionRef.current));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 중복 삭제 방지 확인
|
// 중복 삭제 방지 확인
|
||||||
@@ -38,28 +56,68 @@ export const useDeleteTransaction = (
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 전역 상태 초기화 (새 삭제 작업 시작)
|
||||||
|
deleteCompletedRef.current = false;
|
||||||
|
|
||||||
|
// 안전장치: 2초 이상 진행 중인 다른 삭제 작업이 있으면 모두 정리
|
||||||
|
if (pendingDeletionRef.current.size > 0) {
|
||||||
|
console.warn('오래된 삭제 작업 정리');
|
||||||
|
clearAllPendingDeletions();
|
||||||
|
clearAllTimeouts();
|
||||||
|
}
|
||||||
|
|
||||||
// pendingDeletionRef에 추가
|
// pendingDeletionRef에 추가
|
||||||
pendingDeletionRef.current.add(id);
|
pendingDeletionRef.current.add(id);
|
||||||
|
|
||||||
// 트랜잭션 삭제 실행
|
// 삭제 작업 시간 제한 설정 (5초)
|
||||||
const result = await deleteTransactionHandler(id);
|
const deletePromise = new Promise<boolean>(async (resolve) => {
|
||||||
|
try {
|
||||||
// 삭제 작업이 완료되면 타임아웃 설정 (안전장치)
|
// 트랜잭션 삭제 실행
|
||||||
clearTimeout(timeoutRef.current[id]); // 기존 타임아웃 제거
|
const result = await deleteTransactionHandler(id);
|
||||||
timeoutRef.current[id] = setTimeout(() => {
|
|
||||||
if (pendingDeletionRef.current.has(id)) {
|
// 결과 반환 전 약간의 지연 (UI 상태 안정화)
|
||||||
console.warn('삭제 작업 완료 후 정리:', id);
|
setTimeout(() => {
|
||||||
pendingDeletionRef.current.delete(id);
|
resolve(result);
|
||||||
delete timeoutRef.current[id];
|
}, 100);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('삭제 작업 실행 오류:', error);
|
||||||
|
resolve(false);
|
||||||
}
|
}
|
||||||
}, 2000); // 2초 후 상태 정리
|
});
|
||||||
|
|
||||||
|
// 타임아웃 프로미스 (5초)
|
||||||
|
const timeoutPromise = new Promise<boolean>((resolve) => {
|
||||||
|
timeoutRef.current[id] = setTimeout(() => {
|
||||||
|
console.warn('삭제 작업 시간 초과:', id);
|
||||||
|
|
||||||
|
// 타임아웃 시 모든 상태 정리
|
||||||
|
if (pendingDeletionRef.current.has(id)) {
|
||||||
|
pendingDeletionRef.current.delete(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
delete timeoutRef.current[id];
|
||||||
|
resolve(false);
|
||||||
|
}, 5000);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Promise.race를 사용하여 둘 중 하나가 먼저 완료되면 처리
|
||||||
|
const result = await Promise.race([deletePromise, timeoutPromise]);
|
||||||
|
|
||||||
|
// 성공적으로 완료되면 타임아웃 취소
|
||||||
|
clearTimeout(timeoutRef.current[id]);
|
||||||
|
delete timeoutRef.current[id];
|
||||||
|
|
||||||
|
console.log('삭제 작업 완료:', id, '결과:', result);
|
||||||
|
|
||||||
|
// 작업 완료 표시
|
||||||
|
deleteCompletedRef.current = true;
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('트랜잭션 삭제 오류:', error);
|
console.error('트랜잭션 삭제 오류:', error);
|
||||||
|
|
||||||
// 오류 발생 시 상태 초기화 (중요: 반드시 해제 필요)
|
// 오류 발생 시 상태 정리
|
||||||
if (pendingDeletionRef.current) {
|
if (pendingDeletionRef.current.has(id)) {
|
||||||
pendingDeletionRef.current.delete(id);
|
pendingDeletionRef.current.delete(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,20 +135,15 @@ export const useDeleteTransaction = (
|
|||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}, [deleteTransactionHandler]);
|
}, [deleteTransactionHandler, clearAllPendingDeletions, clearAllTimeouts]);
|
||||||
|
|
||||||
// 컴포넌트 언마운트 시 타임아웃 정리
|
// 안전장치: 컴포넌트 언마운트 또는 의존성 변경 시 모든 타임아웃 및 진행 중인 작업 정리
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
// 모든 타임아웃 정리
|
clearAllTimeouts();
|
||||||
Object.values(timeoutRef.current).forEach(timeout => {
|
clearAllPendingDeletions();
|
||||||
clearTimeout(timeout);
|
|
||||||
});
|
|
||||||
|
|
||||||
// 모든 대기 중인 삭제 작업 해제
|
|
||||||
pendingDeletionRef.current.clear();
|
|
||||||
};
|
};
|
||||||
}, []);
|
}, [clearAllTimeouts, clearAllPendingDeletions]);
|
||||||
|
|
||||||
return deleteTransaction;
|
return deleteTransaction;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -35,10 +35,10 @@ const Transactions = () => {
|
|||||||
}
|
}
|
||||||
}, [budgetData, isLoading]);
|
}, [budgetData, isLoading]);
|
||||||
|
|
||||||
// 트랜잭션 삭제 핸들러 - 간소화 및 안정성 개선
|
// 트랜잭션 삭제 핸들러 - 완전히 개선된 버전
|
||||||
const handleTransactionDelete = async (id: string): Promise<boolean> => {
|
const handleTransactionDelete = async (id: string): Promise<boolean> => {
|
||||||
// 이미 처리 중인 경우 작업 무시
|
// 이미 처리 중인 경우 작업 무시하고 false 반환
|
||||||
if (isProcessing || deletingId === id) {
|
if (isProcessing || deletingId) {
|
||||||
console.log('이미 삭제 작업이 진행 중입니다:', deletingId);
|
console.log('이미 삭제 작업이 진행 중입니다:', deletingId);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -50,32 +50,44 @@ const Transactions = () => {
|
|||||||
|
|
||||||
console.log('트랜잭션 삭제 시작 (ID):', id);
|
console.log('트랜잭션 삭제 시작 (ID):', id);
|
||||||
|
|
||||||
// deleteTransaction 함수 호출 (Promise<boolean> 반환 예상)
|
// 삭제 시간 제한 설정 (5초)
|
||||||
const success = await deleteTransaction(id);
|
const timeoutPromise = new Promise<boolean>((_, reject) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
reject(new Error('삭제 작업 시간 초과'));
|
||||||
|
}, 5000);
|
||||||
|
});
|
||||||
|
|
||||||
|
// deleteTransaction 함수 호출 또는 타임아웃 처리
|
||||||
|
const deletePromise = deleteTransaction(id);
|
||||||
|
|
||||||
|
// Promise.race를 사용하여 둘 중 하나가 먼저 완료되면 처리
|
||||||
|
const success = await Promise.race([deletePromise, timeoutPromise])
|
||||||
|
.catch(error => {
|
||||||
|
console.error('삭제 작업 오류 또는 시간 초과:', error);
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
console.log('삭제 작업 결과:', success);
|
console.log('삭제 작업 결과:', success);
|
||||||
|
return Boolean(success);
|
||||||
return success;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('트랜잭션 삭제 처리 중 오류:', error);
|
console.error('트랜잭션 삭제 처리 중 오류:', error);
|
||||||
|
|
||||||
// 오류 발생 시 토스트 표시
|
|
||||||
toast({
|
toast({
|
||||||
title: "삭제 실패",
|
title: "삭제 실패",
|
||||||
description: "지출 삭제 중 오류가 발생했습니다.",
|
description: "지출 삭제 중 오류가 발생했습니다.",
|
||||||
variant: "destructive"
|
variant: "destructive"
|
||||||
});
|
});
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
// 상태 초기화 (약간의 지연 후)
|
// 상태 초기화 (즉시 처리)
|
||||||
|
setIsProcessing(false);
|
||||||
|
setDeletingId(null);
|
||||||
|
|
||||||
|
// 사용자 경험 개선을 위해 약간의 지연 후 데이터 새로고침
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
setIsProcessing(false);
|
if (!isLoading) {
|
||||||
setDeletingId(null);
|
refreshTransactions();
|
||||||
|
}
|
||||||
// 데이터 새로고침 (삭제 후 UI 업데이트)
|
}, 300);
|
||||||
refreshTransactions();
|
|
||||||
}, 500);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user