Refactor transaction deletion logic
Compare and align transaction deletion logic between homepage and transactions page to resolve issues on the transactions page.
This commit is contained in:
@@ -9,9 +9,6 @@ import TransactionsContent from '@/components/transactions/TransactionsContent';
|
||||
import { Transaction } from '@/components/TransactionCard';
|
||||
import { toast } from '@/hooks/useToast.wrapper';
|
||||
|
||||
/**
|
||||
* 거래내역 페이지 - 성능 및 안정성 개선 버전
|
||||
*/
|
||||
const Transactions = () => {
|
||||
const {
|
||||
transactions,
|
||||
@@ -23,130 +20,60 @@ const Transactions = () => {
|
||||
handleNextMonth,
|
||||
refreshTransactions,
|
||||
totalExpenses,
|
||||
deleteTransaction
|
||||
} = useTransactions();
|
||||
|
||||
const { budgetData } = useBudget();
|
||||
const [isDataLoaded, setIsDataLoaded] = useState(false);
|
||||
const { budgetData, deleteTransaction: budgetDeleteTransaction } = useBudget();
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||
|
||||
// 더블 클릭 방지용 래퍼
|
||||
const deletionTimestampRef = useRef<Record<string, number>>({});
|
||||
// 페이지 가시성 상태 추적
|
||||
const isVisibleRef = useRef(true);
|
||||
// 타임아웃 ID 관리
|
||||
const timeoutIdsRef = useRef<Array<ReturnType<typeof setTimeout>>>([]);
|
||||
|
||||
// 타임아웃 정리 함수
|
||||
const clearAllTimeouts = useCallback(() => {
|
||||
timeoutIdsRef.current.forEach(id => clearTimeout(id));
|
||||
timeoutIdsRef.current = [];
|
||||
}, []);
|
||||
const processingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// 데이터 로드 상태 관리
|
||||
useEffect(() => {
|
||||
if (budgetData && !isLoading) {
|
||||
setIsDataLoaded(true);
|
||||
}
|
||||
}, [budgetData, isLoading]);
|
||||
|
||||
// 트랜잭션 삭제 핸들러 - 완전히 개선된 버전
|
||||
// 삭제 핸들러 - 홈 페이지와 동일한 방식으로 구현
|
||||
const handleTransactionDelete = useCallback(async (id: string): Promise<boolean> => {
|
||||
// 삭제 중 또는 다른 작업 중인지 확인
|
||||
if (isProcessing || deletingId) {
|
||||
console.log('이미 삭제 작업이 진행 중입니다:', deletingId);
|
||||
return true;
|
||||
if (isProcessing) {
|
||||
console.log('이미 삭제 작업이 진행 중입니다');
|
||||
return false;
|
||||
}
|
||||
|
||||
// 더블 클릭 방지 (2초 이내 동일 요청)
|
||||
const now = Date.now();
|
||||
const lastDeletionTime = deletionTimestampRef.current[id] || 0;
|
||||
if (now - lastDeletionTime < 2000) {
|
||||
console.log('중복 삭제 요청 무시:', id);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 타임스탬프 업데이트
|
||||
deletionTimestampRef.current[id] = now;
|
||||
|
||||
|
||||
try {
|
||||
// 삭제 상태 설정
|
||||
setIsProcessing(true);
|
||||
setDeletingId(id);
|
||||
|
||||
console.log('트랜잭션 삭제 시작 (ID):', id);
|
||||
// 타임아웃 설정
|
||||
processingTimeoutRef.current = setTimeout(() => {
|
||||
setIsProcessing(false);
|
||||
}, 2000);
|
||||
|
||||
// BudgetContext의 삭제 함수 사용
|
||||
budgetDeleteTransaction(id);
|
||||
|
||||
// 삭제 함수 호출 (Promise로 래핑)
|
||||
const deletePromise = deleteTransaction(id);
|
||||
|
||||
// 안전한 타임아웃 설정 (5초)
|
||||
const timeoutPromise = new Promise<boolean>((resolve) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
console.warn('삭제 타임아웃 - 강제 완료');
|
||||
resolve(true); // UI는 이미 업데이트되었으므로 성공으로 간주
|
||||
}, 5000);
|
||||
|
||||
// 타임아웃 ID 관리
|
||||
timeoutIdsRef.current.push(timeoutId);
|
||||
});
|
||||
|
||||
// 둘 중 하나가 먼저 완료되면 반환
|
||||
const result = await Promise.race([deletePromise, timeoutPromise]);
|
||||
return result;
|
||||
// 삭제 후 데이터 새로고침
|
||||
setTimeout(() => {
|
||||
refreshTransactions();
|
||||
}, 500);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('삭제 처리 중 오류:', error);
|
||||
console.error('트랜잭션 삭제 중 오류:', error);
|
||||
toast({
|
||||
title: "삭제 실패",
|
||||
description: "지출 삭제 중 오류가 발생했습니다.",
|
||||
variant: "destructive",
|
||||
duration: 1500
|
||||
description: "지출 항목을 삭제하는데 문제가 발생했습니다.",
|
||||
variant: "destructive"
|
||||
});
|
||||
return false;
|
||||
} finally {
|
||||
// 상태 초기화
|
||||
if (processingTimeoutRef.current) {
|
||||
clearTimeout(processingTimeoutRef.current);
|
||||
}
|
||||
setIsProcessing(false);
|
||||
setDeletingId(null);
|
||||
|
||||
// 새로고침 (약간 지연)
|
||||
const refreshTimeoutId = setTimeout(() => {
|
||||
if (!isLoading && isVisibleRef.current) {
|
||||
refreshTransactions();
|
||||
}
|
||||
}, 500);
|
||||
|
||||
// 타임아웃 ID 관리
|
||||
timeoutIdsRef.current.push(refreshTimeoutId);
|
||||
}
|
||||
}, [isProcessing, deletingId, deleteTransaction, isLoading, refreshTransactions]);
|
||||
}, [isProcessing, budgetDeleteTransaction, refreshTransactions]);
|
||||
|
||||
// 페이지 포커스/가시성 관리
|
||||
// 컴포넌트 언마운트 시 타임아웃 정리
|
||||
useEffect(() => {
|
||||
const handleVisibilityChange = () => {
|
||||
isVisibleRef.current = document.visibilityState === 'visible';
|
||||
|
||||
if (isVisibleRef.current && !isProcessing) {
|
||||
console.log('거래내역 페이지 보임 - 데이터 새로고침');
|
||||
refreshTransactions();
|
||||
}
|
||||
};
|
||||
|
||||
const handleFocus = () => {
|
||||
if (!isProcessing && isVisibleRef.current) {
|
||||
console.log('거래내역 페이지 포커스 - 데이터 새로고침');
|
||||
refreshTransactions();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
window.addEventListener('focus', handleFocus);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
window.removeEventListener('focus', handleFocus);
|
||||
clearAllTimeouts();
|
||||
if (processingTimeoutRef.current) {
|
||||
clearTimeout(processingTimeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, [refreshTransactions, isProcessing, clearAllTimeouts]);
|
||||
}, []);
|
||||
|
||||
// 트랜잭션을 날짜별로 그룹화
|
||||
const groupTransactionsByDate = useCallback((transactions: Transaction[]): Record<string, Transaction[]> => {
|
||||
@@ -165,7 +92,6 @@ const Transactions = () => {
|
||||
return grouped;
|
||||
}, []);
|
||||
|
||||
// 로딩이나 처리 중이면 비활성화된 UI 상태 표시
|
||||
const isDisabled = isLoading || isProcessing;
|
||||
const groupedTransactions = groupTransactionsByDate(transactions);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user