Heart Button
components/HeartButton.js
import { firestore, auth, increment } from '../lib/firebase';
import { useDocument } from 'react-firebase-hooks/firestore';
// Allows user to heart or like a post
export default function Heart({ postRef }) {
// Listen to heart document for currently logged in user
const heartRef = postRef.collection('hearts').doc(auth.currentUser.uid);
const [heartDoc] = useDocument(heartRef);
// Create a user-to-post relationship
const addHeart = async () => {
const uid = auth.currentUser.uid;
const batch = firestore.batch();
batch.update(postRef, { heartCount: increment(1) });
batch.set(heartRef, { uid });
await batch.commit();
};
// Remove a user-to-post relationship
const removeHeart = async () => {
const batch = firestore.batch();
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>
);
}
Usage in a Component
pages/username/slug.js
import HeartButton from '../../components/HeartButton';
import AuthCheck from '../../components/AuthCheck';
import Link from 'next/link';
// ...
<AuthCheck
fallback={
<Link href="/enter">
<button>đ Sign Up</button>
</Link>
}
>
<HeartButton postRef={postRef} />
</AuthCheck>