Optimistic toggle button with Stimulus “revert on failure”

1053
0

I like optimistic UI for tiny interactions (like “star” or “follow”) because it makes the interface feel instant. The tradeoff is handling failure cleanly. I implement this with Stimulus: flip CSS + text immediately, then submit a Turbo request in the background via fetch including the CSRF token. If the response isn’t 2xx, revert the UI to its previous state. This avoids writing a full SPA state layer while still delivering good UX. The server remains the source of truth, and the button can still be progressively enhanced: if JS is off, it’s just a normal button_to.