I am new to PWA and have been testing my PWA project using firebase console database. When offline, I have code to save my post data in indexedDB
when i submit my post data to saved later when there is WiFi(online). It did save the data in indexedDB
when no WiFi found, but when i turn on my WiFi, it doesn't post my data in realtime. When i submit new post data when wifi on(online), background sync codes do post saved data from indexedDB
with newly post data in real time. But i want my background sync codes to post automatically when WiFi is turned on(after offline).
Here is my service worker code for background sync:
self.addEventListener('sync', function(event) {
console.log('Background syncing...', event);
if (event.tag === 'sync-new-posts') {
console.log('Syncing new Posts...');
event.waitUntil(
readAllData('sync-posts') // function to read all saved data which had been saved when offline
.then(function(data) {
for (var dt of data) {
fetch('xxx some firebase post url xxx', { // fetching for sending saved data to firebase database
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
id: dt.id,
title: dt.title,
content: dt.content
})
})
.then(function(res) {
console.log('Sent data', res);
if (res.ok) {
res.json()
.then(function (resData) {
deleteItemFromData('sync-posts', resData .id); // function for deleting saved post data from indexedDB as we donot need after realtime post is saved when online.
});
}
})
.catch(function(err) {
console.log('Error while sending data', err);
});
}
})
);
}
});
I don't know what's go wrong. If anyone need more of my codes of my posting codes or serviceworker codes for more clarity, please do ask. Please help me with this as i am stuck in this.