46 lines
1.1 KiB
JavaScript
46 lines
1.1 KiB
JavaScript
import { createContext, useContext, useState } from 'react';
|
|
|
|
const LoanContext = createContext(null);
|
|
|
|
export function LoanProvider({ children }) {
|
|
const [loans, setLoans] = useState(() => {
|
|
const saved = localStorage.getItem('loans');
|
|
return saved ? JSON.parse(saved) : [];
|
|
});
|
|
|
|
function addLoan(book, borrowerUsername, dueDate) {
|
|
const loan = {
|
|
loanId: crypto.randomUUID(),
|
|
bookId: book.isbn,
|
|
bookTitle: book.title,
|
|
bookAuthor: book.author,
|
|
borrowerUsername,
|
|
dueDate,
|
|
status: 'ACTIVE',
|
|
loanedAt: new Date().toISOString(),
|
|
};
|
|
const updated = [...loans, loan];
|
|
setLoans(updated);
|
|
localStorage.setItem('loans', JSON.stringify(updated));
|
|
return loan;
|
|
}
|
|
|
|
function returnLoan(loanId) {
|
|
const updated = loans.map(l =>
|
|
l.loanId === loanId ? { ...l, status: 'RETURNED' } : l
|
|
);
|
|
setLoans(updated);
|
|
localStorage.setItem('loans', JSON.stringify(updated));
|
|
}
|
|
|
|
return (
|
|
<LoanContext.Provider value={{ loans, addLoan, returnLoan }}>
|
|
{children}
|
|
</LoanContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useLoans() {
|
|
return useContext(LoanContext);
|
|
}
|