Created
December 2, 2019 10:32
-
-
Save kuzyo/7b740138c2558c82c06ebde22d03b982 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://reacttraining.com/blog/blog-claps-and-lessons-on-hooks/ | |
function BlogClaps({ slug }) { | |
const [loading, setLoading] = useState(true) | |
const [claps, setClaps] = useState(0) | |
const [queueClaps, setQueueClaps] = useState(0) | |
useEffect(() => { | |
// When the component loads, get the current clap count | |
getBlogPostClaps(slug).then(claps => { | |
setLoading(false) | |
// Set the clap count | |
setClaps(claps) | |
}) | |
}, [slug]) | |
// This effect gets called anytime the queueClaps gets changed | |
useEffect(() => { | |
if (queueClaps > 0) { | |
// Create a timeout if queueClaps was bigger than 0 | |
const timeout = setTimeout(() => { | |
// After 700ms, send the network request and then | |
// update the claps based on the network, reset | |
// queueClaps | |
addBlogPostClaps(slug, queueClaps).then(claps => { | |
setClaps(claps) | |
setQueueClaps(0) | |
}) | |
}, 700) | |
return () => clearTimeout(timeout) | |
} | |
}, [queueClaps]) | |
function clap() { | |
setQueueClaps(queueClaps + 1) | |
} | |
// Notice the changes to the JSX too: | |
return ( | |
<div> | |
<button onClick={clap}> | |
{loading | |
? 'Loading...' | |
: `${(claps + queueClaps).toLocaleString()} claps`} | |
</button> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment