Refactor useBudgetState into smaller files
Refactors the `useBudgetState.ts` file into smaller, more manageable files to improve code organization and maintainability. No functionality is changed.
This commit is contained in:
69
src/contexts/budget/hooks/useBudgetDataState.ts
Normal file
69
src/contexts/budget/hooks/useBudgetDataState.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { BudgetData, BudgetPeriod } from '../types';
|
||||
import {
|
||||
loadBudgetDataFromStorage,
|
||||
saveBudgetDataToStorage,
|
||||
clearAllBudgetData
|
||||
} from '../storageUtils';
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
import {
|
||||
calculateUpdatedBudgetData,
|
||||
calculateSpentAmounts
|
||||
} from '../budgetUtils';
|
||||
|
||||
// 예산 데이터 상태 관리 훅
|
||||
export const useBudgetDataState = (transactions: any[]) => {
|
||||
const [budgetData, setBudgetData] = useState<BudgetData>(loadBudgetDataFromStorage());
|
||||
const [selectedTab, setSelectedTab] = useState<BudgetPeriod>("daily");
|
||||
|
||||
// 지출 금액 업데이트
|
||||
useEffect(() => {
|
||||
// 스토리지에서 데이터 로드
|
||||
const loadedBudgetData = loadBudgetDataFromStorage();
|
||||
|
||||
// 지출 금액 업데이트
|
||||
const updatedBudgetData = calculateSpentAmounts(transactions, loadedBudgetData);
|
||||
|
||||
// 상태 및 스토리지 모두 업데이트
|
||||
setBudgetData(updatedBudgetData);
|
||||
saveBudgetDataToStorage(updatedBudgetData);
|
||||
|
||||
// 로컬 이벤트 발생 (다른 컴포넌트에서 변경 감지하도록)
|
||||
window.dispatchEvent(new Event('budgetDataUpdated'));
|
||||
}, [transactions]);
|
||||
|
||||
// 예산 목표 업데이트 함수
|
||||
const handleBudgetGoalUpdate = useCallback((
|
||||
type: BudgetPeriod,
|
||||
amount: number,
|
||||
newCategoryBudgets?: Record<string, number>
|
||||
) => {
|
||||
// 월간 예산 직접 업데이트 (카테고리 예산이 없는 경우)
|
||||
if (!newCategoryBudgets) {
|
||||
const updatedBudgetData = calculateUpdatedBudgetData(budgetData, type, amount);
|
||||
setBudgetData(updatedBudgetData);
|
||||
saveBudgetDataToStorage(updatedBudgetData);
|
||||
|
||||
toast({
|
||||
title: "목표 업데이트 완료",
|
||||
description: `${type === 'daily' ? '일일' : type === 'weekly' ? '주간' : '월간'} 목표가 ${amount.toLocaleString()}원으로 설정되었습니다.`
|
||||
});
|
||||
}
|
||||
}, [budgetData]);
|
||||
|
||||
// 예산 데이터 초기화 함수
|
||||
const resetBudgetData = useCallback(() => {
|
||||
clearAllBudgetData();
|
||||
setBudgetData(loadBudgetDataFromStorage());
|
||||
console.log('예산 데이터가 초기화되었습니다.');
|
||||
}, []);
|
||||
|
||||
return {
|
||||
budgetData,
|
||||
selectedTab,
|
||||
setSelectedTab,
|
||||
handleBudgetGoalUpdate,
|
||||
resetBudgetData
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user