AHA demos
← All demos

Optimistic like button

The heart fills the instant you click. The server catches up a moment later and has the final word.

One like per browser. The total is shared with everyone who visits.

What to look at

Click and two things happen. Alpine flips liked and bumps count right away, so the UI feels instant. At the same time htmx posts to the server.

The server toggles your like in D1 and returns the button again with the real values. hx-swap="outerHTML" replaces the whole button, Alpine state included. Whatever the server says wins. The server adds 600ms of lag so you can see the two steps.

This is the whole optimistic UI pattern: guess locally, confirm from the server, let the response overwrite the guess. If the request fails, the swap never happens and you can catch it with htmx:response:error.

Try clicking fast. Every click sends a request and every response is authoritative, so the count settles on the truth.

Source

Loading source…

Every file of this demo, as it runs. Or browse it on GitHub ↗