Firebase Error

bookshelf 프로젝트를 하던 중 발생한 문제. document를 삭제했을 때 이런 오류가 발생했다. 오류에서 친절하게 알려주고 있듯이 document 삭제 후 이미 존재하지 않는(삭제된) document에 접근하고 있다는 것.
const updateRating = async (isbn13: string, ratingCount: number) => {
try {
if (currentUser) {
const arr: Book[] = [];
const bookDocRef = doc(db, "users", currentUser, "books", isbn13);
const querySnapshot = await getDocs(
collection(db, "users", currentUser, "books")
);
querySnapshot.forEach((doc) => {
arr.push(doc.data() as Book);
});
await updateDoc(bookDocRef, { rating: ratingCount });
}
} catch (err) {
console.error(err);
}
};
문제는 updateRating() 함수 때문이었는데,
책(document)을 삭제함 -> firestore onSnapshot 함수 호출 -> 전체 bookList가 변경됨
때문이 아닐까.. 해서 코드를 변경했다.
문제 해결
collection 전체 데이터 중 해당 isbn을 가진 책이 존재하는지 확인하고 존재할 경우에만 updateDoc을 하는 것으로 변경하였다.
const updateRating = async (isbn13: string, ratingCount: number) => {
try {
if (currentUser) {
const arr: Book[] = [];
const bookDocRef = doc(db, "users", currentUser, "books", isbn13);
const querySnapshot = await getDocs(
collection(db, "users", currentUser, "books")
);
querySnapshot.forEach((doc) => {
arr.push(doc.data() as Book);
});
// isbn이 존재하지 않으면 실행되지 않도록 함.
if (arr.find((v) => v.isbn13 == isbn13)) await updateDoc(bookDocRef, { rating: ratingCount });
}
} catch (err) {
console.error(err);
}
};
'Recap > bookshelf' 카테고리의 다른 글
| [리팩토링 #03.] useMemo()로 리팩토링하여 성능 최적화하기 (0) | 2024.02.28 |
|---|---|
| [리팩토링 #02.] 아토믹 디자인 패턴 Atomic Design Pattern 적용하기 (0) | 2024.02.25 |
| [리팩토링 #01.] 중복되는 코드를 Dumb component로 만들어 리팩토링하기 (0) | 2024.02.25 |
| [8일차] 프로젝트 끝! 다크모드, 페이지 상단으로 이동하기 (0) | 2024.01.31 |
| [7일차] skeleton UI 적용하고 리팩토링하기 (0) | 2024.01.31 |