Fix data persistence issue
Addresses a problem where budget and expense data was not being saved correctly.
This commit is contained in:
@@ -15,7 +15,9 @@ interface BudgetContextType {
|
||||
current: number;
|
||||
total: number;
|
||||
}>;
|
||||
addTransaction: (transaction: Transaction) => void;
|
||||
updateTransaction: (transaction: Transaction) => void;
|
||||
deleteTransaction: (id: string) => void;
|
||||
handleBudgetGoalUpdate: (type: BudgetPeriod, amount: number, newCategoryBudgets?: Record<string, number>) => void;
|
||||
resetBudgetData?: () => void; // 선택적 필드로 추가
|
||||
}
|
||||
|
||||
@@ -4,74 +4,95 @@ import { DEFAULT_CATEGORY_BUDGETS, getInitialBudgetData } from './budgetUtils';
|
||||
|
||||
// 로컬 스토리지에서 트랜잭션 불러오기
|
||||
export const loadTransactionsFromStorage = (): Transaction[] => {
|
||||
const storedTransactions = localStorage.getItem('transactions');
|
||||
if (storedTransactions) {
|
||||
try {
|
||||
try {
|
||||
const storedTransactions = localStorage.getItem('transactions');
|
||||
if (storedTransactions) {
|
||||
return JSON.parse(storedTransactions);
|
||||
} catch (error) {
|
||||
console.error('트랜잭션 데이터 파싱 오류:', error);
|
||||
return [];
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('트랜잭션 데이터 파싱 오류:', error);
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
// 트랜잭션 저장
|
||||
export const saveTransactionsToStorage = (transactions: Transaction[]): void => {
|
||||
localStorage.setItem('transactions', JSON.stringify(transactions));
|
||||
try {
|
||||
localStorage.setItem('transactions', JSON.stringify(transactions));
|
||||
console.log('트랜잭션 저장 완료, 항목 수:', transactions.length);
|
||||
} catch (error) {
|
||||
console.error('트랜잭션 저장 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 모든 트랜잭션 삭제
|
||||
export const clearAllTransactions = (): void => {
|
||||
localStorage.removeItem('transactions');
|
||||
// 빈 배열을 저장하여 확실히 초기화
|
||||
localStorage.setItem('transactions', JSON.stringify([]));
|
||||
try {
|
||||
localStorage.removeItem('transactions');
|
||||
// 빈 배열을 저장하여 확실히 초기화
|
||||
localStorage.setItem('transactions', JSON.stringify([]));
|
||||
console.log('모든 트랜잭션이 삭제되었습니다.');
|
||||
} catch (error) {
|
||||
console.error('트랜잭션 삭제 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 카테고리 예산 불러오기
|
||||
export const loadCategoryBudgetsFromStorage = (): Record<string, number> => {
|
||||
const storedCategoryBudgets = localStorage.getItem('categoryBudgets');
|
||||
if (storedCategoryBudgets) {
|
||||
try {
|
||||
return JSON.parse(storedCategoryBudgets);
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 데이터 파싱 오류:', error);
|
||||
return DEFAULT_CATEGORY_BUDGETS;
|
||||
try {
|
||||
const storedCategoryBudgets = localStorage.getItem('categoryBudgets');
|
||||
if (storedCategoryBudgets) {
|
||||
const parsed = JSON.parse(storedCategoryBudgets);
|
||||
console.log('카테고리 예산 로드 완료:', parsed);
|
||||
return parsed;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 데이터 파싱 오류:', error);
|
||||
}
|
||||
|
||||
// 새 사용자를 위한 기본 카테고리 예산 저장
|
||||
console.log('기본 카테고리 예산 설정');
|
||||
saveCategoryBudgetsToStorage(DEFAULT_CATEGORY_BUDGETS);
|
||||
return DEFAULT_CATEGORY_BUDGETS;
|
||||
};
|
||||
|
||||
// 카테고리 예산 저장
|
||||
export const saveCategoryBudgetsToStorage = (categoryBudgets: Record<string, number>): void => {
|
||||
localStorage.setItem('categoryBudgets', JSON.stringify(categoryBudgets));
|
||||
try {
|
||||
localStorage.setItem('categoryBudgets', JSON.stringify(categoryBudgets));
|
||||
console.log('카테고리 예산 저장 완료:', categoryBudgets);
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 저장 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 모든 카테고리 예산 삭제
|
||||
export const clearAllCategoryBudgets = (): void => {
|
||||
localStorage.removeItem('categoryBudgets');
|
||||
// 기본값으로 재설정
|
||||
saveCategoryBudgetsToStorage(DEFAULT_CATEGORY_BUDGETS);
|
||||
try {
|
||||
localStorage.removeItem('categoryBudgets');
|
||||
// 기본값으로 재설정
|
||||
saveCategoryBudgetsToStorage(DEFAULT_CATEGORY_BUDGETS);
|
||||
console.log('카테고리 예산이 초기화되었습니다.');
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 삭제 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 예산 데이터 불러오기
|
||||
export const loadBudgetDataFromStorage = (): BudgetData => {
|
||||
const storedBudgetData = localStorage.getItem('budgetData');
|
||||
if (storedBudgetData) {
|
||||
try {
|
||||
return JSON.parse(storedBudgetData);
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 파싱 오류:', error);
|
||||
const initialData = getInitialBudgetData();
|
||||
saveBudgetDataToStorage(initialData);
|
||||
return initialData;
|
||||
try {
|
||||
const storedBudgetData = localStorage.getItem('budgetData');
|
||||
if (storedBudgetData) {
|
||||
const parsed = JSON.parse(storedBudgetData);
|
||||
console.log('예산 데이터 로드 완료');
|
||||
return parsed;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 파싱 오류:', error);
|
||||
}
|
||||
|
||||
// 새 사용자를 위한 기본 예산 데이터 저장
|
||||
console.log('기본 예산 데이터 설정');
|
||||
const initialData = getInitialBudgetData();
|
||||
saveBudgetDataToStorage(initialData);
|
||||
return initialData;
|
||||
@@ -79,15 +100,25 @@ export const loadBudgetDataFromStorage = (): BudgetData => {
|
||||
|
||||
// 예산 데이터 저장
|
||||
export const saveBudgetDataToStorage = (budgetData: BudgetData): void => {
|
||||
localStorage.setItem('budgetData', JSON.stringify(budgetData));
|
||||
try {
|
||||
localStorage.setItem('budgetData', JSON.stringify(budgetData));
|
||||
console.log('예산 데이터 저장 완료');
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 저장 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 모든 예산 데이터 삭제
|
||||
export const clearAllBudgetData = (): void => {
|
||||
localStorage.removeItem('budgetData');
|
||||
// 기본값으로 재설정
|
||||
const initialData = getInitialBudgetData();
|
||||
saveBudgetDataToStorage(initialData);
|
||||
try {
|
||||
localStorage.removeItem('budgetData');
|
||||
// 기본값으로 재설정
|
||||
const initialData = getInitialBudgetData();
|
||||
saveBudgetDataToStorage(initialData);
|
||||
console.log('예산 데이터가 초기화되었습니다.');
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 삭제 오류:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 모든 데이터 초기화 (첫 로그인 상태)
|
||||
|
||||
@@ -61,9 +61,21 @@ export const useBudgetState = () => {
|
||||
|
||||
// 지출 계산 및 업데이트
|
||||
useEffect(() => {
|
||||
const updatedBudgetData = calculateSpentAmounts(transactions, budgetData);
|
||||
// 스토리지에서 데이터 로드
|
||||
const loadedBudgetData = loadBudgetDataFromStorage();
|
||||
|
||||
// 지출 금액 업데이트
|
||||
const updatedBudgetData = calculateSpentAmounts(transactions, loadedBudgetData);
|
||||
|
||||
// 상태 및 스토리지 모두 업데이트
|
||||
setBudgetData(updatedBudgetData);
|
||||
saveBudgetDataToStorage(updatedBudgetData);
|
||||
|
||||
// 트랜잭션 변경 내용도 저장
|
||||
saveTransactionsToStorage(transactions);
|
||||
|
||||
// 로컬 이벤트 발생 (다른 컴포넌트에서 변경 감지하도록)
|
||||
window.dispatchEvent(new Event('budgetDataUpdated'));
|
||||
}, [transactions]);
|
||||
|
||||
// 카테고리별 예산 및 지출 계산
|
||||
@@ -91,11 +103,27 @@ export const useBudgetState = () => {
|
||||
}
|
||||
};
|
||||
|
||||
saveBudgetDataToStorage(updatedBudgetData);
|
||||
// 저장 과정 강화 - 예산 데이터 저장
|
||||
try {
|
||||
saveBudgetDataToStorage(updatedBudgetData);
|
||||
console.log('예산 데이터가 저장되었습니다:', updatedBudgetData);
|
||||
} catch (error) {
|
||||
console.error('예산 데이터 저장 중 오류:', error);
|
||||
}
|
||||
|
||||
return updatedBudgetData;
|
||||
});
|
||||
|
||||
saveCategoryBudgetsToStorage(categoryBudgets);
|
||||
// 저장 과정 강화 - 카테고리 예산 저장
|
||||
try {
|
||||
saveCategoryBudgetsToStorage(categoryBudgets);
|
||||
console.log('카테고리 예산이 저장되었습니다:', categoryBudgets);
|
||||
} catch (error) {
|
||||
console.error('카테고리 예산 저장 중 오류:', error);
|
||||
}
|
||||
|
||||
// 로컬 이벤트 발생 (다른 컴포넌트에서 변경 감지하도록)
|
||||
window.dispatchEvent(new Event('categoryBudgetsUpdated'));
|
||||
}, [categoryBudgets]);
|
||||
|
||||
// 카테고리별 지출 계산
|
||||
@@ -108,6 +136,15 @@ export const useBudgetState = () => {
|
||||
// 카테고리 예산이 직접 업데이트된 경우
|
||||
if (newCategoryBudgets) {
|
||||
setCategoryBudgets(newCategoryBudgets);
|
||||
|
||||
// 저장 과정 추가
|
||||
saveCategoryBudgetsToStorage(newCategoryBudgets);
|
||||
|
||||
toast({
|
||||
title: "카테고리 예산 업데이트 완료",
|
||||
description: "카테고리별 예산이 저장되었습니다."
|
||||
});
|
||||
|
||||
return; // 카테고리 예산이 변경되면 useEffect에서 자동으로 budgetData가 업데이트됩니다
|
||||
}
|
||||
|
||||
@@ -121,6 +158,7 @@ export const useBudgetState = () => {
|
||||
});
|
||||
|
||||
setCategoryBudgets(updatedCategoryBudgets);
|
||||
saveCategoryBudgetsToStorage(updatedCategoryBudgets);
|
||||
} else {
|
||||
// 일일이나 주간 예산이 직접 업데이트되는 경우
|
||||
const updatedBudgetData = calculateUpdatedBudgetData(budgetData, type, amount);
|
||||
@@ -134,6 +172,15 @@ export const useBudgetState = () => {
|
||||
});
|
||||
};
|
||||
|
||||
// 트랜잭션 추가 함수 추가
|
||||
const addTransaction = (newTransaction: Transaction) => {
|
||||
setTransactions(prev => {
|
||||
const updated = [newTransaction, ...prev];
|
||||
saveTransactionsToStorage(updated);
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
// 트랜잭션 업데이트 처리
|
||||
const updateTransaction = (updatedTransaction: Transaction) => {
|
||||
setTransactions(prev => {
|
||||
@@ -145,15 +192,26 @@ export const useBudgetState = () => {
|
||||
});
|
||||
};
|
||||
|
||||
// 트랜잭션 삭제 함수 추가
|
||||
const deleteTransaction = (transactionId: string) => {
|
||||
setTransactions(prev => {
|
||||
const updated = prev.filter(transaction => transaction.id !== transactionId);
|
||||
saveTransactionsToStorage(updated);
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
transactions,
|
||||
categoryBudgets,
|
||||
budgetData,
|
||||
selectedTab,
|
||||
setSelectedTab,
|
||||
addTransaction,
|
||||
updateTransaction,
|
||||
deleteTransaction,
|
||||
handleBudgetGoalUpdate,
|
||||
getCategorySpending,
|
||||
resetBudgetData // 새로 추가된 리셋 함수
|
||||
resetBudgetData
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user