Attached is the reference from the firebase
I am saving data as here
enter image description here
const productRef = await addDoc(collection(db, `rating_book/${product.bk_ID}/ratings`), {
bookId: product.bk_ID,
date: Timestamp.now(),
rating: rating,
token: JSON.parse(localStorage.getItem('user')!).token,
username: JSON.parse(localStorage.getItem('user')!).username
});
This is another snapshot for complete picture from firebase.
enter image description here
I am trying to fetch data but i am not getting data here. why?
const fetchTopRatedBookIds = async() => {
try {
const ratingsSnapshot = await getDocs(collection(db, 'rating_book'));
const bookRatings: { [bookId: string]: number[] } = {};
await Promise.all(ratingsSnapshot.docs.map(async (doc) => {
const ratings = doc.data().ratings as number[];
bookRatings[doc.id] = ratings;
console.log(`Book ID: ${doc.id}, Ratings: ${ratings}`);
}));
const averageRatings = Object.entries(bookRatings).map(([bookId, ratings]) => ({
bookId,
averageRating: ratings.reduce((acc, curr) => acc + curr, 0) / ratings.length,
}));
console.log('Average Ratings:', averageRatings);
const sortedBooks = averageRatings.sort((a, b) => b.averageRating - a.averageRating).slice(0, 3).map(entry => entry.bookId);
console.log('Sorted Books:', sortedBooks);
return sortedBooks;
} catch (error) {
console.error('Error fetching details', error);
return [];
}
};
Any suggestions is appreciated.
New contributor
Rida Fatima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.