-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathHeartButton.tsx
41 lines (30 loc) · 1.21 KB
/
HeartButton.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { auth } from '@lib/firebase';
import { useDocument } from '@lib/hooks';
//import { useDocument } from 'react-firebase-hooks/firestore';
import { increment, writeBatch, doc, getFirestore } from "firebase/firestore";
// Allows user to heart or like a post
export default function Heart({ postRef }: any) {
const uid: any = auth?.currentUser?.uid;
// Listen to heart document for currently logged in user
const heartRef = doc(getFirestore(), postRef.path, 'hearts', uid);
const [heartDoc] = useDocument(heartRef);
// Create a user-to-post relationship
const addHeart = async () => {
const batch = writeBatch(getFirestore());
batch.update(postRef, { heartCount: increment(1) });
batch.set(heartRef, { uid });
await batch.commit();
};
// Remove a user-to-post relationship
const removeHeart = async () => {
const batch = writeBatch(getFirestore());
batch.update(postRef, { heartCount: increment(-1) });
batch.delete(heartRef);
await batch.commit();
};
return heartDoc?.exists() ? (
<button onClick={removeHeart}>💔 Unheart</button>
) : (
<button onClick={addHeart}>💗 Heart</button>
);
}