Skip to content

Instantly share code, notes, and snippets.

@benjick
Last active July 1, 2021 08:08
Show Gist options
  • Save benjick/84e7846d43c86a2d8fb167e3961aff23 to your computer and use it in GitHub Desktop.
Save benjick/84e7846d43c86a2d8fb167e3961aff23 to your computer and use it in GitHub Desktop.
const db = firebase.firestore();
const FieldValue = firebase.firestore.FieldValue;
const myUserID = '123456';

Creating a post

await db.collection('posts').add({
    title: 'Hello world!',
    postedBy: myUserID,
    likedBy: {},
    likes: 0,
})

Has liked a post

const post = await db.collection('posts').doc('test').get();
const hasLiked = post.likedBy[myUserID] === true

Liking a post

await db.collection('posts').doc('test').update({
    likes: FieldValue.increment(1),
    [`likedBy.${myUserID}`]: true,
})

Unliking a post

await db.collection('posts').doc('test').update({
    likes: FieldValue.increment(-1),
    [`likedBy.${myUserID}`]: FieldValue.delete(),
})
function Post({id}) {
const [post, setPost] = useState(null)
const [hasLiked, setHasLiked] = useState(false)
useEffect(() => {
const unsubscribe = db.collection('posts').doc(id).onSnapshot((doc) => {
const data = doc.data();
setPost(data);
setHasLiked(data.likedBy[myUserID] === true)
});
return () => unsubscribe()
}, [])
function toggleLike() {
if (hasLiked) {
db.collection('posts').doc('test').update({
likes: FieldValue.increment(-1),
[`likedBy.${myUserID}`]: FieldValue.delete(),
})
} else {
db.collection('posts').doc('test').update({
likes: FieldValue.increment(1),
[`likedBy.${myUserID}`]: true,
})
}
}
if (!post) {
return 'Loading...'
}
return (
<div>
<h1>{{post.title}}</h1>
<button onClick={toggleLike}>{hasLiked ? 'unlike' : 'like'}</button>
<p>Likes: {{post.likes}}</p>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment