Fix budget update issues
Addresses delayed notifications and data loss after budget updates and page transitions.
This commit is contained in:
@@ -16,14 +16,26 @@ import {
|
||||
export const useBudgetDataState = (transactions: any[]) => {
|
||||
const [budgetData, setBudgetData] = useState<BudgetData>(loadBudgetDataFromStorage());
|
||||
const [selectedTab, setSelectedTab] = useState<BudgetPeriod>("daily");
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
// 초기 로드 및 이벤트 리스너 설정
|
||||
useEffect(() => {
|
||||
const loadBudget = () => {
|
||||
console.log('예산 데이터 로드 시도 중...');
|
||||
const loadedData = loadBudgetDataFromStorage();
|
||||
console.log('예산 데이터 로드됨:', loadedData);
|
||||
setBudgetData(loadedData);
|
||||
try {
|
||||
console.log('예산 데이터 로드 시도 중...');
|
||||
const loadedData = loadBudgetDataFromStorage();
|
||||
console.log('예산 데이터 로드됨:', loadedData);
|
||||
setBudgetData(loadedData);
|
||||
|
||||
// 최근 데이터 로드 시간 기록
|
||||
localStorage.setItem('lastBudgetDataLoadTime', new Date().toISOString());
|
||||
|
||||
if (!isInitialized) {
|
||||
setIsInitialized(true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 로드 중 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 초기 로드
|
||||
@@ -39,30 +51,56 @@ export const useBudgetDataState = (transactions: any[]) => {
|
||||
|
||||
window.addEventListener('budgetDataUpdated', () => handleBudgetUpdate());
|
||||
window.addEventListener('storage', handleBudgetUpdate);
|
||||
window.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
console.log('페이지 보임: 예산 데이터 새로고침');
|
||||
loadBudget();
|
||||
}
|
||||
});
|
||||
window.addEventListener('focus', () => {
|
||||
console.log('창 포커스: 예산 데이터 새로고침');
|
||||
loadBudget();
|
||||
});
|
||||
|
||||
// 주기적 데이터 검사 (1초마다)
|
||||
const intervalId = setInterval(() => {
|
||||
const lastSaveTime = localStorage.getItem('lastBudgetSaveTime');
|
||||
const lastLoadTime = localStorage.getItem('lastBudgetDataLoadTime');
|
||||
|
||||
if (lastSaveTime && lastLoadTime && new Date(lastSaveTime) > new Date(lastLoadTime)) {
|
||||
console.log('새로운 저장 감지됨, 데이터 다시 로드...');
|
||||
loadBudget();
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('budgetDataUpdated', () => handleBudgetUpdate());
|
||||
window.removeEventListener('storage', handleBudgetUpdate);
|
||||
window.removeEventListener('visibilitychange', () => {});
|
||||
window.removeEventListener('focus', () => loadBudget());
|
||||
clearInterval(intervalId);
|
||||
};
|
||||
}, []);
|
||||
}, [isInitialized]);
|
||||
|
||||
// 트랜잭션 변경 시 지출 금액 업데이트
|
||||
useEffect(() => {
|
||||
if (transactions.length > 0) {
|
||||
console.log('트랜잭션 변경으로 인한 예산 데이터 업데이트. 트랜잭션 수:', transactions.length);
|
||||
// 지출 금액 업데이트
|
||||
const updatedBudgetData = calculateSpentAmounts(transactions, budgetData);
|
||||
|
||||
// 상태 및 스토리지 모두 업데이트
|
||||
setBudgetData(updatedBudgetData);
|
||||
saveBudgetDataToStorage(updatedBudgetData);
|
||||
try {
|
||||
// 지출 금액 업데이트
|
||||
const updatedBudgetData = calculateSpentAmounts(transactions, budgetData);
|
||||
|
||||
// 상태 및 스토리지 모두 업데이트
|
||||
setBudgetData(updatedBudgetData);
|
||||
saveBudgetDataToStorage(updatedBudgetData);
|
||||
|
||||
// 저장 시간 업데이트
|
||||
localStorage.setItem('lastBudgetSaveTime', new Date().toISOString());
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 업데이트 중 오류:', error);
|
||||
}
|
||||
}
|
||||
}, [transactions]);
|
||||
}, [transactions, budgetData]);
|
||||
|
||||
// 예산 목표 업데이트 함수
|
||||
const handleBudgetGoalUpdate = useCallback((
|
||||
@@ -70,26 +108,42 @@ export const useBudgetDataState = (transactions: any[]) => {
|
||||
amount: number,
|
||||
newCategoryBudgets?: Record<string, number>
|
||||
) => {
|
||||
console.log(`예산 목표 업데이트: ${type}, 금액: ${amount}`);
|
||||
// 월간 예산 직접 업데이트 (카테고리 예산이 없는 경우)
|
||||
if (!newCategoryBudgets) {
|
||||
const updatedBudgetData = calculateUpdatedBudgetData(budgetData, type, amount);
|
||||
console.log('새 예산 데이터:', updatedBudgetData);
|
||||
setBudgetData(updatedBudgetData);
|
||||
saveBudgetDataToStorage(updatedBudgetData);
|
||||
|
||||
try {
|
||||
console.log(`예산 목표 업데이트: ${type}, 금액: ${amount}`);
|
||||
// 월간 예산 직접 업데이트 (카테고리 예산이 없는 경우)
|
||||
if (!newCategoryBudgets) {
|
||||
const updatedBudgetData = calculateUpdatedBudgetData(budgetData, type, amount);
|
||||
console.log('새 예산 데이터:', updatedBudgetData);
|
||||
setBudgetData(updatedBudgetData);
|
||||
saveBudgetDataToStorage(updatedBudgetData);
|
||||
|
||||
// 저장 시간 업데이트
|
||||
localStorage.setItem('lastBudgetSaveTime', new Date().toISOString());
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('예산 목표 업데이트 중 오류:', error);
|
||||
toast({
|
||||
title: "목표 업데이트 완료",
|
||||
description: `${type === 'daily' ? '일일' : type === 'weekly' ? '주간' : '월간'} 목표가 ${amount.toLocaleString()}원으로 설정되었습니다.`
|
||||
title: "예산 업데이트 실패",
|
||||
description: "예산 목표를 업데이트하는데 문제가 발생했습니다.",
|
||||
variant: "destructive"
|
||||
});
|
||||
}
|
||||
}, [budgetData]);
|
||||
|
||||
// 예산 데이터 초기화 함수
|
||||
const resetBudgetData = useCallback(() => {
|
||||
console.log('예산 데이터 초기화');
|
||||
clearAllBudgetData();
|
||||
setBudgetData(loadBudgetDataFromStorage());
|
||||
try {
|
||||
console.log('예산 데이터 초기화');
|
||||
clearAllBudgetData();
|
||||
setBudgetData(loadBudgetDataFromStorage());
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 초기화 중 오류:', error);
|
||||
toast({
|
||||
title: "예산 초기화 실패",
|
||||
description: "예산 데이터를 초기화하는데 문제가 발생했습니다.",
|
||||
variant: "destructive"
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 예산 데이터 변경 시 로그 기록
|
||||
|
||||
Reference in New Issue
Block a user