Offline Form Handling
You'll learn how to capture form submissions when offline and automatically sync them once the user reconnects.
When users fill out forms without an internet connection, their work shouldn't vanish into thin air. Offline form handling saves submitted data locally (using IndexedDB or localStorage), then automatically sends it to your server when connectivity returns—no user intervention required.
Think of it like dropping a letter in a mailbox when the post office is closed. The letter stays safely in the box until service resumes, then gets delivered automatically.
How It Works
1. Detect the submission attempt: Listen for form submit events and check if the user is offline (!navigator.onLine).
2. Store locally: Save the form data to IndexedDB or localStorage with a timestamp and unique identifier.
3. Prevent default submission: Use event.preventDefault() to stop the browser from trying to submit immediately.
4. Show feedback: Display a message confirming the data is queued for submission.
5. Listen for reconnection: Add an event listener for the online event to detect when connectivity returns.
6. Auto-submit: When online, retrieve all queued submissions from local storage and send them via fetch(). Remove successfully submitted entries from storage.
Building on What You Know
You've already learned queue failed requests (#2329) and optimistic UI updates (#2330). Offline form handling combines both: queue the submission optimistically, update the UI to show "saved locally," then sync in the background when possible. Use the same online/offline detection patterns (#2323) you've practiced.
Key Takeaway: Offline form handling preserves user input by saving submissions locally when offline and automatically syncing them to the server when connectivity is restored, creating a seamless experience regardless of network conditions.