I am trying to develop a web app using Laravel and vue.js where I can sync data from firestore even if I am offline. I have seen in the features of firestore that it provides this feature. But I dont know how to this feature into my project. I have cloned suhasrkms/laravel-with-firestore for Firestore in Laravel. But main problem i am facing is i dont know how to add offline code/persistence. I tried to add the code in resources/js/offline-persistence.js which is provided in firestore doc. I have tried to add code as well in my blade file.
Kindly provide me the solution, your reply will be valuable for me.
<script type="text/javascript">
firebase.firestore().enablePersistence()
.catch((err) => alert(Something failed for enablePersistence, code: ${err.code}));
firebase.firestore().collection('test')
.onSnapshot(snaps => {
if (snaps.empty) { return; }
const preDataElm = document.getElementById("preData");
while (preDataElm.firstChild) {
preDataElm.removeChild(preDataElm.firstChild);
}
let list = snaps.docs.map(snap => {
return {id: snap.id, ...snap.data()};
});
let newElm = document.createElement("PRE");
newElm.innerText = JSON.stringify(list, null, 2);
return preDataElm.appendChild(newElm);
});
function tryMe() {
document.getElementById("result").innerHtml = "";
firebase.firestore()
.collection('test')
.add({test: new Date().toString()})
.then((docRef) => alert(Data inserted successfuly ID: ${docRef.id}));
}
</script>
To add offline code/persistence , you need to enable or disable offline persistence while initializing Cloud Firestore, as stated in the documentation:
For Android and iOS, offline persistence is enabled by default. To disable persistence, set the PersistenceEnabled option to false.
For the web, offline persistence is disabled by default.To enable persistence, call the enablePersistence method. Cloud Firestore's cache isn't automatically cleared between sessions.Consequently, if your web app handles sensitive information, make sure to ask the user if they're on a trusted device before enabling persistence.
You can also refer to the stackoverflow case1 and case2 where a similar issue has been faced by the OP which got resolved by setting up the persistence as:
FirebaseDatabase.getInstance().setPersistenceEnabled(true);