41 lines
1.0 KiB
JavaScript
41 lines
1.0 KiB
JavaScript
import { createContext, useContext, useState } from 'react';
|
|
|
|
const ReviewContext = createContext(null);
|
|
|
|
export function ReviewProvider({ children }) {
|
|
const [reviews, setReviews] = useState(() => {
|
|
const saved = localStorage.getItem('reviews');
|
|
return saved ? JSON.parse(saved) : [];
|
|
});
|
|
|
|
function addReview(bookId, bookTitle, username, rating, comment) {
|
|
const review = {
|
|
reviewId: crypto.randomUUID(),
|
|
bookId,
|
|
bookTitle,
|
|
username,
|
|
rating,
|
|
comment,
|
|
createdAt: new Date().toISOString(),
|
|
};
|
|
const updated = [...reviews, review];
|
|
setReviews(updated);
|
|
localStorage.setItem('reviews', JSON.stringify(updated));
|
|
return review;
|
|
}
|
|
|
|
function getReviewsByBook(bookId) {
|
|
return reviews.filter(r => String(r.bookId) === String(bookId));
|
|
}
|
|
|
|
return (
|
|
<ReviewContext.Provider value={{ reviews, addReview, getReviewsByBook }}>
|
|
{children}
|
|
</ReviewContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useReviews() {
|
|
return useContext(ReviewContext);
|
|
}
|