Upload with Optimistic UI Updates
What you'll learn: How to make file uploads feel instant by updating the UI immediately, then gracefully handling server failures.
When users upload files, they expect immediate feedback—not a spinning loader while they wait for the server to respond. Optimistic UI updates mean you show the uploaded file as "successful" in your interface before the server confirms it, making the experience feel lightning-fast.
The Core Idea
Think of it like ordering food at a restaurant: an optimistic approach means the waiter writes down your order and gives you a receipt immediately, assuming the kitchen will successfully prepare it. If something goes wrong later, they come back and apologize. This is far better than making you wait at the counter while they check with the chef.
How It Works
- Immediately display the file in your UI when the user selects it (using preview techniques you learned earlier)
- Start the upload in the background (using XMLHttpRequest or fetch with progress tracking)
- Mark as "uploading" with visual indicators like progress bars
- Assume success and mark the file as complete once upload finishes
- Rollback on failure: if the server rejects the file (validation error, network issue, etc.), remove it from the UI and show an error message
The Rollback Strategy
This is the critical piece: you must handle failures gracefully. Store enough state (file ID, temporary UI element reference) to remove or mark the file as failed if the server responds with an error. Users should see a clear message explaining what went wrong, with an option to retry.
Key Takeaway: Optimistic UI updates make uploads feel instant by showing immediate feedback and only reverting changes when the server reports a problem—creating a responsive experience that handles both success and failure smoothly.