91 lines
2.9 KiB
TypeScript
91 lines
2.9 KiB
TypeScript
|
|
import { useState, useEffect } from 'react';
|
|
import { Transaction } from '../types';
|
|
import { loadTransactionsFromStorage, saveTransactionsToStorage } from '../storage/transactionStorage';
|
|
import { v4 as uuidv4 } from 'uuid';
|
|
|
|
/**
|
|
* 트랜잭션 상태를 관리하는 훅
|
|
* 트랜잭션 목록을 로드하고 추가, 수정, 삭제 기능을 제공합니다.
|
|
*/
|
|
export const useTransactionState = () => {
|
|
// 로컬 스토리지에서 초기 트랜잭션 데이터 로드
|
|
const [transactions, setTransactions] = useState<Transaction[]>([]);
|
|
|
|
// 초기 로드
|
|
useEffect(() => {
|
|
try {
|
|
const storedTransactions = loadTransactionsFromStorage();
|
|
console.log('로컬 스토리지에서 트랜잭션 로드:', storedTransactions?.length || 0);
|
|
setTransactions(storedTransactions || []);
|
|
} catch (error) {
|
|
console.error('트랜잭션 로드 중 오류 발생:', error);
|
|
// 오류 발생 시 빈 배열로 초기화
|
|
setTransactions([]);
|
|
}
|
|
}, []);
|
|
|
|
// 트랜잭션 변경 시 로컬 스토리지에 저장
|
|
useEffect(() => {
|
|
try {
|
|
if (transactions && transactions.length > 0) {
|
|
console.log('트랜잭션 저장 중:', transactions.length);
|
|
saveTransactionsToStorage(transactions);
|
|
}
|
|
} catch (error) {
|
|
console.error('트랜잭션 저장 중 오류 발생:', error);
|
|
}
|
|
}, [transactions]);
|
|
|
|
// 트랜잭션 추가
|
|
const addTransaction = (transaction: Transaction) => {
|
|
try {
|
|
const newTransaction = {
|
|
...transaction,
|
|
id: transaction.id || uuidv4(),
|
|
localTimestamp: new Date().toISOString()
|
|
};
|
|
setTransactions(prevTransactions => [...(prevTransactions || []), newTransaction]);
|
|
console.log('트랜잭션 추가됨:', newTransaction);
|
|
} catch (error) {
|
|
console.error('트랜잭션 추가 중 오류 발생:', error);
|
|
}
|
|
};
|
|
|
|
// 트랜잭션 업데이트
|
|
const updateTransaction = (updatedTransaction: Transaction) => {
|
|
try {
|
|
setTransactions(prevTransactions =>
|
|
(prevTransactions || []).map(transaction =>
|
|
transaction.id === updatedTransaction.id
|
|
? { ...updatedTransaction, localTimestamp: new Date().toISOString() }
|
|
: transaction
|
|
)
|
|
);
|
|
console.log('트랜잭션 업데이트됨:', updatedTransaction.id);
|
|
} catch (error) {
|
|
console.error('트랜잭션 업데이트 중 오류 발생:', error);
|
|
}
|
|
};
|
|
|
|
// 트랜잭션 삭제
|
|
const deleteTransaction = (id: string) => {
|
|
try {
|
|
setTransactions(prevTransactions =>
|
|
(prevTransactions || []).filter(transaction => transaction.id !== id)
|
|
);
|
|
console.log('트랜잭션 삭제됨:', id);
|
|
} catch (error) {
|
|
console.error('트랜잭션 삭제 중 오류 발생:', error);
|
|
}
|
|
};
|
|
|
|
return {
|
|
transactions,
|
|
setTransactions,
|
|
addTransaction,
|
|
updateTransaction,
|
|
deleteTransaction
|
|
};
|
|
};
|