Skip to content

Instantly share code, notes, and snippets.

@ilxanlar
Last active April 7, 2021 15:15
Show Gist options
  • Save ilxanlar/200e0150a6eb67ac52300946de811fb6 to your computer and use it in GitHub Desktop.
Save ilxanlar/200e0150a6eb67ac52300946de811fb6 to your computer and use it in GitHub Desktop.
import React, { useState } from 'react'
const toggleLikeTweet = async (tweetId: number) => {
// Send a request to API
}
function LikeTweet({ tweetId, tweetIsLiked }) {
const [isLiked, setIsLiked] = useState(tweetIsLiked)
useEffect(
() => {
setIsLiked(tweetIsLiked)
},
[tweetIsLiked]
)
const handleClick = async () => {
// Optimistically toggle like in local state
setIsLiked(prevIsLiked => !prevIsLiked)
try {
// Tell API to toggle like tweet
await toggleLikeTweet(tweetId)
// Successfully toggled like API then:
// Update tweet object or refetch tweets list
} catch (error) {
// Request failed so toggle local state again to rollback
setIsLiked(prevIsLiked => !prevIsLiked)
}
}
return (
<button onClick={handleClick}>
{isLiked ? 'Dislike' : 'Like'}
</buttton>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment