How to Sync Your Client and Server After Being Offline
PWAs have become more and more commonplace. People want to access your content in uncertain conditions or even when there’s no internet connection at all. To battle this, we have service workers that can help you eliminate the problems of being offline. But what happens once the connection is back and users have pending changes?
Most of the time, these changes are lost. Since there’s no connection, they are not saved to a database. But can we change this? The answer is yes. This is the time when you want to sync the changes to ensure they are kept and nothing is lost.
So how do we do this? Everything starts when things go offline.
Detecting Offline State
For detecting network changes, we have some options. First, you can add event listeners for online
and offline
changes:
window.addEventListener('offline', () => { ... });
window.addEventListener('online', () => { ... });
This is especially useful when you want to give some feedback to the user about the changes in network conditions.
Apart from event listeners, we can also check the value of navigator.onLine
. If this value turns out to be true, we can save changes locally only to sync them later with the server.
Queue Updates
To queue network requests, we need to store information on the user’s machine. We also need to account for page refreshes or even closing the browser altogether. This can be done with the use of localStorage
. Let’s create an offlineService
that can catch network requests to later reuse them for syncing:
const offlineService = {
getQueue() {
return JSON.parse(localStorage.getItem('queue') || '[]');
},
deferRequest(payload) {
const queue = this.getQueue();
queue.push(payload);
localStorage.setItem('queue', JSON.stringify(queue));
},
clearQueue() {
localStorage.removeItem('queue');
}
};
For this, we can create an object with three different methods:
getQueue
for getting thelocalStorage
itemqueue
. Here, we can fallback to a string representation of an empty array in case we don’t have aqueue
inlocalStorage
.deferRequest
for adding network requests to thequeue
.clearQueue
for removing the pending network requests.
Note that we have to use JSON.parse
and JSON.stringify
to be able to save to localStorage
.
By exporting the object and importing it to a service that handles API requests, we can use navigator.onLine
to check the network condition:
// Service that receives all requests to the API
APIRequest(params) {
if (!navigator.onLine) {
offlineService.deferRequest(params);
} else {
return fetch(params.url, {
body: params.body,
method: params.method,
headers: params.headers
}).then(response => {
return response.json();
}).catch(error => {
console.log(error);
});
}
}
And we either use our newly created offlineService
to defer requests or we continue sending them as usual. Every time a request is made, this will create a new object in the queue
array with the request URL, body, method, and headers—everything that is needed to later sync pending changes with the server.
Syncing With Database
The last thing to do is to finally sync the changes with the server once the connection is restored:
window.addEventListener('online', () => {
if (offlineService.getQueue().length) {
const deferredRequests = offlineService.getQueue();
deferredRequests.forEach(async payload => await APIRequest(payload));
offlineService.clearQueue();
}
});
First, we can check if there’s anything in the array just to be sure. If there is, we get it, and for each request that has been queued, we call the function that handles the API requests with the payload provided. Then we can clear the queue since nothing needs to updated again.
Summary
All that’s left to do is to check if everything works as expected. I also added some CSS animation to it to show the user that something is going on in the background:
When I go offline, first the notification comes up. This is due to the event listener added to the offline
event. Then I try to add a couple of items and set the connection back to online
in the Network tab. And we get back four requests for the four changes.
This combined with a service worker and PWA configuration can really take the offline experience of your application to the next level. Users can confidently keep on working even when the connection is lost. And since all information is stored inside localStorage
, this information will survive even if you close the tab.
Thank you for reading through. Are there any ways you try to deal with being offline? If so, let us know in the comments section below.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: