Upvote button with optimistic updates and rollback on failure
Build the upvote button for a discussion post. It should feel instant: the button and the vote count change the moment the user clicks, and the request to save the vote runs in the background. If saving fails, the UI quietly goes back to how it was and tells the user.
The starter code includes the endpoint and the post’s starting state:
const VOTE_URL = '/api/posts/314/vote';
const INITIAL_VOTE = { voted: false, votes: 128 };
POST /api/posts/314/vote
Content-Type: application/json
{ "voted": true }
200 OK
{ "voted": true, "votes": 140 }
The response holds the server’s view of the vote and the post’s latest total, which may include other people’s votes. Any non-2xx status, a network error, or a body without a boolean voted and a number votes is a failure.
<button> whose text is Upvote when the user hasn’t voted and Upvoted when they have (an icon next to it is fine). It has aria-pressed="true" when voted and aria-pressed="false" otherwise.N votes, or 1 vote when it is exactly 1.fetch(VOTE_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ voted }) }) with the new voted value.disabled attribute or aria-disabled="true") and further clicks do nothing.voted and votes, and enable the button.Could not save your vote. Try again., and enable the button.Start [Upvote] 128 votes
Click [Upvoted] 129 votes (disabled, request in flight)
server: 140 [Upvoted] 140 votes
Click [Upvote] 139 votes (body { "voted": false })
server: 500 [Upvoted] 140 votes "Could not save your vote. Try again."
Click again [Upvote] 139 votes (error hidden, new request)
INITIAL_VOTE.fetch doesn’t reject on HTTP errors. Check response.ok yourself.The tests replace window.fetch with a stub that holds each request until the test answers it, click your button, and read the screen like a user would. You don’t need test ids, specific class names, or an exact HTML structure. They check that:
<button> (or role="button" element) whose text contains Upvote or Upvoted, and its aria-pressed matches.N votes / 1 vote and Could not save your vote appear as described.fetch is called with VOTE_URL as its first argument and an options object with method: 'POST' and a JSON string body.Capitalization and extra spacing don’t matter.