call(back)
FrontendmediumSign in to star problems

Like Button

Build a like button that talks to a server.

The starter's api.js provides toggleLike(action), a stand-in for a POST: it resolves after a short delay for "like" or "unlike", and fails about half the time with an Error whose message says why. Three buttons render on the page; each must work on its own.

Requirements

  • Default: grey outline heart. Hovered: red outline. Liked: filled heart on a red background. Use #f00 and #888; the look is not the point, the states are.
  • Clicking in the default state enters a loading state: the heart becomes a spinner, a second click does nothing, and toggleLike("like") is sent. On success the button becomes liked. On failure it returns to default (or hovered, if the pointer is still over it) and the error message appears under the button.
  • Clicking while liked does the reverse with "unlike".
  • The visible label stays Like in every state. aria-pressed is false until the server confirms a like and true after, and a screen reader hears the error without focus moving.
  • initialLiked starts the button liked. optimistic flips the heart as soon as it is clicked and flips it back if the request fails.

Hints

Hint 1

Three pieces of state cover every picture: liked (what the server has confirmed), pending, and error. Hovered is CSS, not state.

Hint 2

Guard the click with pending rather than relying on disabled: a disabled button drops keyboard focus, so whoever pressed Enter loses their place when the answer arrives. aria-disabled tells assistive tech the same thing.

Hint 3

Optimistic means setting the next value before the request and setting it back in catch. Anything that runs after an await should first check the component is still mounted.

Asked at

Similar Problems6