Files
cally/hooks/firebase/useUpdateFeedback.ts
Milan Paunovic c411990312 Fixes
2024-12-15 16:46:26 +01:00

66 lines
1.7 KiB
TypeScript

import { useAuthContext } from "@/contexts/AuthContext";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import firestore from "@react-native-firebase/firestore";
import { IFeedback } from "@/contexts/FeedbackContext";
interface UpdateFeedbackParams {
id: number;
changes: Partial<IFeedback>;
}
export const useUpdateFeedback = () => {
const { user: currentUser } = useAuthContext();
const queryClient = useQueryClient();
return useMutation({
mutationKey: ["updateFeedback"],
mutationFn: async ({ id, changes }: UpdateFeedbackParams) => {
try {
const snapshot = await firestore()
.collection("Feedbacks")
.where("id", "==", id)
.get();
if (snapshot.empty) {
throw new Error("Feedback not found");
}
const docId = snapshot.docs[0].id;
const feedbackData = snapshot.docs[0].data();
if (feedbackData.creatorId !== currentUser?.uid) {
throw new Error(
"Unauthorized: You can only update your own feedback"
);
}
await firestore()
.collection("Feedbacks")
.doc(docId)
.update({
...changes,
updatedAt: firestore.FieldValue.serverTimestamp(),
lastModifiedBy: currentUser?.uid,
});
return {
id,
...feedbackData,
...changes,
};
} catch (e) {
console.error("Error updating feedback: ", e);
throw e;
}
},
onSuccess: (updatedFeedback) => {
queryClient.invalidateQueries({queryKey: ["feedbacks"]})
queryClient.setQueryData(
["feedback", updatedFeedback.id],
updatedFeedback
);
},
});
};