Fix budget data persistence issue

Addresses the problem where budget data was not persisting across page transitions, causing budget and expense information to disappear from the expense page and only expense data to appear on the analytics page.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-16 07:29:25 +00:00
parent 84553d4fee
commit 23ba0f7e90
5 changed files with 158 additions and 113 deletions

View File

@@ -17,43 +17,63 @@ const Analytics = () => {
const [selectedPeriod, setSelectedPeriod] = useState('이번 달');
const { budgetData, getCategorySpending, transactions } = useBudget();
const isMobile = useIsMobile();
// 데이터 변경 감지를 위한 효과
const [refreshTrigger, setRefreshTrigger] = useState(0);
// 페이지 가시성 변경시 데이터 새로고침
useEffect(() => {
console.log('Analytics 페이지 마운트: 데이터 감지 시작');
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') {
console.log('분석 페이지 보임 - 데이터 새로고침');
setRefreshTrigger(prev => prev + 1);
// 이벤트 발생시켜 데이터 새로고침
try {
window.dispatchEvent(new Event('storage'));
window.dispatchEvent(new Event('transactionUpdated'));
window.dispatchEvent(new Event('budgetDataUpdated'));
window.dispatchEvent(new Event('categoryBudgetsUpdated'));
} catch (e) {
console.error('이벤트 발생 오류:', e);
}
}
};
// 페이지 포커스시 새로고침 이벤트 발생
const handleFocus = () => {
console.log('Analytics 페이지: 창 포커스 감지, 상태 새로고침');
// 상태 리렌더링 트리거를 위한 빈 상태 업데이트
setSelectedPeriod(prev => prev);
};
// 스토리지 변경 감지
const handleStorageChange = () => {
console.log('Analytics 페이지: 스토리지 변경 감지, 상태 새로고침');
setSelectedPeriod(prev => prev);
console.log('분석 페이지 포커스 - 데이터 새로고침');
setRefreshTrigger(prev => prev + 1);
// 이벤트 발생시켜 데이터 새로고침
try {
window.dispatchEvent(new Event('storage'));
window.dispatchEvent(new Event('transactionUpdated'));
window.dispatchEvent(new Event('budgetDataUpdated'));
window.dispatchEvent(new Event('categoryBudgetsUpdated'));
} catch (e) {
console.error('이벤트 발생 오류:', e);
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
window.addEventListener('focus', handleFocus);
window.addEventListener('transactionUpdated', handleStorageChange);
window.addEventListener('budgetDataUpdated', handleStorageChange);
window.addEventListener('categoryBudgetsUpdated', handleStorageChange);
window.addEventListener('storage', handleStorageChange);
window.addEventListener('transactionUpdated', () => setRefreshTrigger(prev => prev + 1));
window.addEventListener('budgetDataUpdated', () => setRefreshTrigger(prev => prev + 1));
window.addEventListener('categoryBudgetsUpdated', () => setRefreshTrigger(prev => prev + 1));
// 컴포넌트 마운트 시 초기 데이터 로드 이벤트 트리거
handleFocus();
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
window.removeEventListener('focus', handleFocus);
window.removeEventListener('transactionUpdated', handleStorageChange);
window.removeEventListener('budgetDataUpdated', handleStorageChange);
window.removeEventListener('categoryBudgetsUpdated', handleStorageChange);
window.removeEventListener('storage', handleStorageChange);
console.log('Analytics 페이지 언마운트: 데이터 감지 중지');
window.removeEventListener('transactionUpdated', () => {});
window.removeEventListener('budgetDataUpdated', () => {});
window.removeEventListener('categoryBudgetsUpdated', () => {});
};
}, []);
// 실제 예산 및 지출 데이터 사용
const totalBudget = budgetData.monthly.targetAmount;
const totalExpense = budgetData.monthly.spentAmount;
const totalBudget = budgetData?.monthly?.targetAmount || 0;
const totalExpense = budgetData?.monthly?.spentAmount || 0;
const savings = Math.max(0, totalBudget - totalExpense);
const savingsPercentage = totalBudget > 0 ? Math.round(savings / totalBudget * 100) : 0;
@@ -63,8 +83,8 @@ const Analytics = () => {
name: category.title,
value: category.current,
color: category.title === '식비' ? '#81c784' :
category.title === '생활비' ? '#AED581' :
category.title === '교통비' ? '#2E7D32' : '#4CAF50'
category.title === '생활비' ? '#AED581' :
category.title === '교통비' ? '#2E7D32' : '#4CAF50'
}));
// 최근 6개월 데이터를 위한 상태
@@ -72,17 +92,12 @@ const Analytics = () => {
// 월별 데이터 생성
useEffect(() => {
console.log('Analytics 페이지: 월별 데이터 생성');
console.log('Analytics 페이지: 월별 데이터 생성', { totalBudget, totalExpense });
// 현재 월 가져오기
const today = new Date();
const currentMonth = today.getMonth();
if (totalBudget === 0 && totalExpense === 0) {
// 모든 데이터가 초기화된 상태라면 빈 배열 사용
setMonthlyData([]);
return;
}
// 최근 6개월 데이터 배열 생성
const last6Months = [];
for (let i = 5; i >= 0; i--) {
@@ -101,7 +116,7 @@ const Analytics = () => {
setMonthlyData(last6Months);
console.log('Analytics 페이지: 월별 데이터 생성 완료', last6Months);
}, [totalBudget, totalExpense]);
}, [totalBudget, totalExpense, refreshTrigger]);
// 이전/다음 기간 이동 처리
const handlePrevPeriod = () => {
@@ -112,15 +127,6 @@ const Analytics = () => {
console.log('다음 기간으로 이동');
};
// 디버깅을 위한 로그
useEffect(() => {
console.log('Analytics 페이지 렌더링:', {
totalBudget,
totalExpense,
categorySpending: categorySpending.length
});
});
return (
<div className="min-h-screen bg-neuro-background pb-24">
<div className="max-w-md mx-auto px-6">
@@ -148,7 +154,7 @@ const Analytics = () => {
<h2 className="text-lg font-semibold mb-3"> </h2>
<MonthlyComparisonChart
monthlyData={monthlyData}
isEmpty={monthlyData.length === 0}
isEmpty={monthlyData.length === 0 || (totalBudget === 0 && totalExpense === 0)}
/>
</div>