Ever clicked a "Like" button and seen it update instantly, even before the server responds? That’s Optimistic UI in action! It makes apps feel super fast by updating the interface immediately, instead of waiting for confirmation from the server.
1. You tap the "Like" button" → The count goes up immediately without waiting.
2. UI updates instantly → The "Like" count goes up immediately.
3. Server request happens in the background → The app sends the request quietly.
4. If the request succeeds → No changes needed, everything is good.
5. If the request fails → The UI rolls back to the previous state (undo the like).
The "Like" Button That Feels Instant
Let's say we have a post, and we want to update the "Likes" instantly when a user clicks the button.
likePost(postId: number) { const post = this.posts.find(p => p.id === postId); if (post) { post.likes += 1; // Instantly update UI } this.http.post(`/api/posts/${postId}/like`, {}).subscribe({ error: () => { if (post) { post.likes -= 1; // Rollback if request fails alert("Oops! Couldn't like the post. Try again."); } } });}
But be careful! If the request fails, you need to rollback the change and show an error message to keep things accurate.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.
Contact Us