Fix data persistence issue
Addresses a bug where budget and expense data were not persisting correctly, leading to data loss when navigating between pages.
This commit is contained in:
@@ -1,5 +1,5 @@
|
|||||||
|
|
||||||
import React from 'react';
|
import React, { useEffect } from 'react';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { EXPENSE_CATEGORIES } from '@/constants/categoryIcons';
|
import { EXPENSE_CATEGORIES } from '@/constants/categoryIcons';
|
||||||
import { useIsMobile } from '@/hooks/use-mobile';
|
import { useIsMobile } from '@/hooks/use-mobile';
|
||||||
@@ -28,6 +28,22 @@ const CategoryBudgetInputs: React.FC<CategoryBudgetInputsProps> = ({
|
|||||||
handleCategoryInputChange(numericValue, category);
|
handleCategoryInputChange(numericValue, category);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 컴포넌트가 마운트될 때 categoryBudgets가 로컬 스토리지에서 다시 로드되도록 이벤트 리스너 설정
|
||||||
|
useEffect(() => {
|
||||||
|
const handleStorageChange = () => {
|
||||||
|
// 부모 컴포넌트에서 데이터가 업데이트되므로 별도 처리 필요 없음
|
||||||
|
console.log('카테고리 예산 데이터 변경 감지됨');
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('categoryBudgetsUpdated', handleStorageChange);
|
||||||
|
window.addEventListener('storage', handleStorageChange);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('categoryBudgetsUpdated', handleStorageChange);
|
||||||
|
window.removeEventListener('storage', handleStorageChange);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-2 w-full">
|
<div className="space-y-2 w-full">
|
||||||
{EXPENSE_CATEGORIES.map(category => (
|
{EXPENSE_CATEGORIES.map(category => (
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import {
|
|||||||
loadBudgetDataFromStorage,
|
loadBudgetDataFromStorage,
|
||||||
saveBudgetDataToStorage,
|
saveBudgetDataToStorage,
|
||||||
clearAllBudgetData
|
clearAllBudgetData
|
||||||
} from '../storageUtils';
|
} from '../storage';
|
||||||
import { toast } from '@/components/ui/use-toast';
|
import { toast } from '@/components/ui/use-toast';
|
||||||
import {
|
import {
|
||||||
calculateUpdatedBudgetData,
|
calculateUpdatedBudgetData,
|
||||||
@@ -17,21 +17,56 @@ export const useBudgetDataState = (transactions: any[]) => {
|
|||||||
const [budgetData, setBudgetData] = useState<BudgetData>(loadBudgetDataFromStorage());
|
const [budgetData, setBudgetData] = useState<BudgetData>(loadBudgetDataFromStorage());
|
||||||
const [selectedTab, setSelectedTab] = useState<BudgetPeriod>("daily");
|
const [selectedTab, setSelectedTab] = useState<BudgetPeriod>("daily");
|
||||||
|
|
||||||
// 지출 금액 업데이트
|
// 지출 금액 업데이트 - 트랜잭션이 변경될 때마다 실행
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// 스토리지에서 데이터 로드
|
|
||||||
const loadedBudgetData = loadBudgetDataFromStorage();
|
|
||||||
|
|
||||||
// 지출 금액 업데이트
|
// 지출 금액 업데이트
|
||||||
const updatedBudgetData = calculateSpentAmounts(transactions, loadedBudgetData);
|
const updatedBudgetData = calculateSpentAmounts(transactions, budgetData);
|
||||||
|
|
||||||
// 상태 및 스토리지 모두 업데이트
|
// 상태 및 스토리지 모두 업데이트
|
||||||
setBudgetData(updatedBudgetData);
|
setBudgetData(updatedBudgetData);
|
||||||
saveBudgetDataToStorage(updatedBudgetData);
|
saveBudgetDataToStorage(updatedBudgetData);
|
||||||
|
}, [transactions, budgetData]);
|
||||||
|
|
||||||
|
// 이벤트 리스너 설정
|
||||||
|
useEffect(() => {
|
||||||
|
const handleBudgetUpdate = () => {
|
||||||
|
const loadedBudgetData = loadBudgetDataFromStorage();
|
||||||
|
setBudgetData(prevData => {
|
||||||
|
// 예산 목표는 로드된 데이터에서 가져오고, 지출 금액은 유지
|
||||||
|
const updatedData = {
|
||||||
|
daily: {
|
||||||
|
...loadedBudgetData.daily,
|
||||||
|
spentAmount: prevData.daily.spentAmount,
|
||||||
|
},
|
||||||
|
weekly: {
|
||||||
|
...loadedBudgetData.weekly,
|
||||||
|
spentAmount: prevData.weekly.spentAmount,
|
||||||
|
},
|
||||||
|
monthly: {
|
||||||
|
...loadedBudgetData.monthly,
|
||||||
|
spentAmount: prevData.monthly.spentAmount,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 남은 금액 재계산
|
||||||
|
updatedData.daily.remainingAmount = updatedData.daily.targetAmount - updatedData.daily.spentAmount;
|
||||||
|
updatedData.weekly.remainingAmount = updatedData.weekly.targetAmount - updatedData.weekly.spentAmount;
|
||||||
|
updatedData.monthly.remainingAmount = updatedData.monthly.targetAmount - updatedData.monthly.spentAmount;
|
||||||
|
|
||||||
|
return updatedData;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
// 로컬 이벤트 발생 (다른 컴포넌트에서 변경 감지하도록)
|
window.addEventListener('budgetDataUpdated', handleBudgetUpdate);
|
||||||
window.dispatchEvent(new Event('budgetDataUpdated'));
|
window.addEventListener('categoryBudgetsUpdated', handleBudgetUpdate);
|
||||||
}, [transactions]);
|
window.addEventListener('storage', handleBudgetUpdate);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('budgetDataUpdated', handleBudgetUpdate);
|
||||||
|
window.removeEventListener('categoryBudgetsUpdated', handleBudgetUpdate);
|
||||||
|
window.removeEventListener('storage', handleBudgetUpdate);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
// 예산 목표 업데이트 함수
|
// 예산 목표 업데이트 함수
|
||||||
const handleBudgetGoalUpdate = useCallback((
|
const handleBudgetGoalUpdate = useCallback((
|
||||||
@@ -45,6 +80,9 @@ export const useBudgetDataState = (transactions: any[]) => {
|
|||||||
setBudgetData(updatedBudgetData);
|
setBudgetData(updatedBudgetData);
|
||||||
saveBudgetDataToStorage(updatedBudgetData);
|
saveBudgetDataToStorage(updatedBudgetData);
|
||||||
|
|
||||||
|
// 이벤트 발생시키기
|
||||||
|
window.dispatchEvent(new Event('budgetDataUpdated'));
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
title: "목표 업데이트 완료",
|
title: "목표 업데이트 완료",
|
||||||
description: `${type === 'daily' ? '일일' : type === 'weekly' ? '주간' : '월간'} 목표가 ${amount.toLocaleString()}원으로 설정되었습니다.`
|
description: `${type === 'daily' ? '일일' : type === 'weekly' ? '주간' : '월간'} 목표가 ${amount.toLocaleString()}원으로 설정되었습니다.`
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import {
|
|||||||
loadCategoryBudgetsFromStorage,
|
loadCategoryBudgetsFromStorage,
|
||||||
saveCategoryBudgetsToStorage,
|
saveCategoryBudgetsToStorage,
|
||||||
clearAllCategoryBudgets
|
clearAllCategoryBudgets
|
||||||
} from '../storage/categoryStorage';
|
} from '../storage';
|
||||||
|
|
||||||
// 카테고리 예산 상태 관리 훅
|
// 카테고리 예산 상태 관리 훅
|
||||||
export const useCategoryBudgetState = () => {
|
export const useCategoryBudgetState = () => {
|
||||||
@@ -12,6 +12,21 @@ export const useCategoryBudgetState = () => {
|
|||||||
loadCategoryBudgetsFromStorage()
|
loadCategoryBudgetsFromStorage()
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// 이벤트 리스너 설정
|
||||||
|
useEffect(() => {
|
||||||
|
const handleCategoryUpdate = () => {
|
||||||
|
setCategoryBudgets(loadCategoryBudgetsFromStorage());
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('categoryBudgetsUpdated', handleCategoryUpdate);
|
||||||
|
window.addEventListener('storage', handleCategoryUpdate);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('categoryBudgetsUpdated', handleCategoryUpdate);
|
||||||
|
window.removeEventListener('storage', handleCategoryUpdate);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
// 카테고리 예산 업데이트 함수
|
// 카테고리 예산 업데이트 함수
|
||||||
const updateCategoryBudgets = useCallback((newCategoryBudgets: Record<string, number>) => {
|
const updateCategoryBudgets = useCallback((newCategoryBudgets: Record<string, number>) => {
|
||||||
setCategoryBudgets(newCategoryBudgets);
|
setCategoryBudgets(newCategoryBudgets);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import {
|
|||||||
loadTransactionsFromStorage,
|
loadTransactionsFromStorage,
|
||||||
saveTransactionsToStorage,
|
saveTransactionsToStorage,
|
||||||
clearAllTransactions
|
clearAllTransactions
|
||||||
} from '../storageUtils';
|
} from '../storage';
|
||||||
import { toast } from '@/components/ui/use-toast';
|
import { toast } from '@/components/ui/use-toast';
|
||||||
|
|
||||||
// 트랜잭션 상태 관리 훅
|
// 트랜잭션 상태 관리 훅
|
||||||
@@ -22,9 +22,17 @@ export const useTransactionState = () => {
|
|||||||
loadTransactions();
|
loadTransactions();
|
||||||
|
|
||||||
// 이벤트 리스너를 추가하여 다른 컴포넌트에서 변경 시 업데이트
|
// 이벤트 리스너를 추가하여 다른 컴포넌트에서 변경 시 업데이트
|
||||||
window.addEventListener('storage', loadTransactions);
|
const handleTransactionUpdate = () => loadTransactions();
|
||||||
|
window.addEventListener('transactionUpdated', handleTransactionUpdate);
|
||||||
|
window.addEventListener('transactionDeleted', handleTransactionUpdate);
|
||||||
|
window.addEventListener('transactionAdded', handleTransactionUpdate);
|
||||||
|
window.addEventListener('storage', handleTransactionUpdate);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
window.removeEventListener('storage', loadTransactions);
|
window.removeEventListener('transactionUpdated', handleTransactionUpdate);
|
||||||
|
window.removeEventListener('transactionDeleted', handleTransactionUpdate);
|
||||||
|
window.removeEventListener('transactionAdded', handleTransactionUpdate);
|
||||||
|
window.removeEventListener('storage', handleTransactionUpdate);
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
@@ -33,6 +41,10 @@ export const useTransactionState = () => {
|
|||||||
setTransactions(prev => {
|
setTransactions(prev => {
|
||||||
const updated = [newTransaction, ...prev];
|
const updated = [newTransaction, ...prev];
|
||||||
saveTransactionsToStorage(updated);
|
saveTransactionsToStorage(updated);
|
||||||
|
|
||||||
|
// 이벤트 발생시키기
|
||||||
|
window.dispatchEvent(new Event('transactionAdded'));
|
||||||
|
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
@@ -44,11 +56,12 @@ export const useTransactionState = () => {
|
|||||||
transaction.id === updatedTransaction.id ? updatedTransaction : transaction
|
transaction.id === updatedTransaction.id ? updatedTransaction : transaction
|
||||||
);
|
);
|
||||||
saveTransactionsToStorage(updated);
|
saveTransactionsToStorage(updated);
|
||||||
|
|
||||||
|
// 이벤트 발생시키기
|
||||||
|
window.dispatchEvent(new Event('transactionUpdated'));
|
||||||
|
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
|
|
||||||
// 로컬 이벤트 발생 (다른 컴포넌트에서 변경 감지하도록)
|
|
||||||
window.dispatchEvent(new Event('transactionUpdated'));
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 트랜잭션 삭제 함수
|
// 트랜잭션 삭제 함수
|
||||||
@@ -56,16 +69,17 @@ export const useTransactionState = () => {
|
|||||||
setTransactions(prev => {
|
setTransactions(prev => {
|
||||||
const updated = prev.filter(transaction => transaction.id !== transactionId);
|
const updated = prev.filter(transaction => transaction.id !== transactionId);
|
||||||
saveTransactionsToStorage(updated);
|
saveTransactionsToStorage(updated);
|
||||||
|
|
||||||
|
// 이벤트 발생시키기
|
||||||
|
window.dispatchEvent(new Event('transactionDeleted'));
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "지출이 삭제되었습니다",
|
||||||
|
description: "지출 항목이 성공적으로 삭제되었습니다.",
|
||||||
|
});
|
||||||
|
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
|
|
||||||
toast({
|
|
||||||
title: "지출이 삭제되었습니다",
|
|
||||||
description: "지출 항목이 성공적으로 삭제되었습니다.",
|
|
||||||
});
|
|
||||||
|
|
||||||
// 로컬 이벤트 발생 (다른 컴포넌트에서 변경 감지하도록)
|
|
||||||
window.dispatchEvent(new Event('transactionDeleted'));
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 트랜잭션 초기화 함수
|
// 트랜잭션 초기화 함수
|
||||||
|
|||||||
@@ -31,6 +31,11 @@ export const saveBudgetDataToStorage = (budgetData: BudgetData): void => {
|
|||||||
try {
|
try {
|
||||||
localStorage.setItem('budgetData', JSON.stringify(budgetData));
|
localStorage.setItem('budgetData', JSON.stringify(budgetData));
|
||||||
console.log('예산 데이터 저장 완료');
|
console.log('예산 데이터 저장 완료');
|
||||||
|
|
||||||
|
// 스토리지 이벤트 수동 트리거 (동일 창에서도 감지하기 위함)
|
||||||
|
window.dispatchEvent(new StorageEvent('storage', {
|
||||||
|
key: 'budgetData'
|
||||||
|
}));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('예산 데이터 저장 오류:', error);
|
console.error('예산 데이터 저장 오류:', error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,11 @@ export const saveCategoryBudgetsToStorage = (categoryBudgets: Record<string, num
|
|||||||
try {
|
try {
|
||||||
localStorage.setItem('categoryBudgets', JSON.stringify(categoryBudgets));
|
localStorage.setItem('categoryBudgets', JSON.stringify(categoryBudgets));
|
||||||
console.log('카테고리 예산 저장 완료:', categoryBudgets);
|
console.log('카테고리 예산 저장 완료:', categoryBudgets);
|
||||||
|
|
||||||
|
// 스토리지 이벤트 수동 트리거 (동일 창에서도 감지하기 위함)
|
||||||
|
window.dispatchEvent(new StorageEvent('storage', {
|
||||||
|
key: 'categoryBudgets'
|
||||||
|
}));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('카테고리 예산 저장 오류:', error);
|
console.error('카테고리 예산 저장 오류:', error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,11 @@ export const saveTransactionsToStorage = (transactions: Transaction[]): void =>
|
|||||||
try {
|
try {
|
||||||
localStorage.setItem('transactions', JSON.stringify(transactions));
|
localStorage.setItem('transactions', JSON.stringify(transactions));
|
||||||
console.log('트랜잭션 저장 완료, 항목 수:', transactions.length);
|
console.log('트랜잭션 저장 완료, 항목 수:', transactions.length);
|
||||||
|
|
||||||
|
// 스토리지 이벤트 수동 트리거 (동일 창에서도 감지하기 위함)
|
||||||
|
window.dispatchEvent(new StorageEvent('storage', {
|
||||||
|
key: 'transactions'
|
||||||
|
}));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('트랜잭션 저장 오류:', error);
|
console.error('트랜잭션 저장 오류:', error);
|
||||||
}
|
}
|
||||||
@@ -37,6 +42,11 @@ export const clearAllTransactions = (): void => {
|
|||||||
// 빈 배열을 저장하여 확실히 초기화
|
// 빈 배열을 저장하여 확실히 초기화
|
||||||
localStorage.setItem('transactions', JSON.stringify([]));
|
localStorage.setItem('transactions', JSON.stringify([]));
|
||||||
console.log('모든 트랜잭션이 삭제되었습니다.');
|
console.log('모든 트랜잭션이 삭제되었습니다.');
|
||||||
|
|
||||||
|
// 스토리지 이벤트 수동 트리거
|
||||||
|
window.dispatchEvent(new StorageEvent('storage', {
|
||||||
|
key: 'transactions'
|
||||||
|
}));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('트랜잭션 삭제 오류:', error);
|
console.error('트랜잭션 삭제 오류:', error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ export const useBudgetState = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// 로컬 이벤트 발생 (다른 컴포넌트에서 변경 감지하도록)
|
// 로컬 이벤트 발생 (다른 컴포넌트에서 변경 감지하도록)
|
||||||
window.dispatchEvent(new Event('categoryBudgetsUpdated'));
|
window.dispatchEvent(new Event('budgetDataUpdated'));
|
||||||
}, [categoryBudgets, budgetData]);
|
}, [categoryBudgets, budgetData]);
|
||||||
|
|
||||||
// 모든 데이터 리셋 함수
|
// 모든 데이터 리셋 함수
|
||||||
|
|||||||
@@ -37,20 +37,15 @@ const Index = () => {
|
|||||||
}
|
}
|
||||||
}, [isInitialized, checkWelcomeDialogState]);
|
}, [isInitialized, checkWelcomeDialogState]);
|
||||||
|
|
||||||
// 트랜잭션 변경 시 페이지 새로고침
|
// 앱이 포커스를 얻었을 때 데이터를 새로고침
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleTransactionAdded = () => {
|
const handleFocus = () => {
|
||||||
console.log('트랜잭션이 추가되었습니다. 페이지를 새로고침합니다.');
|
// 이벤트 발생시켜 데이터 새로고침
|
||||||
// 컨텍스트에서 최신 데이터 가져오기
|
window.dispatchEvent(new Event('storage'));
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addEventListener('transactionAdded', handleTransactionAdded);
|
window.addEventListener('focus', handleFocus);
|
||||||
window.addEventListener('budgetDataUpdated', handleTransactionAdded);
|
return () => window.removeEventListener('focus', handleFocus);
|
||||||
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener('transactionAdded', handleTransactionAdded);
|
|
||||||
window.removeEventListener('budgetDataUpdated', handleTransactionAdded);
|
|
||||||
};
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
Reference in New Issue
Block a user