I have a application in codeigniter and angular framework. All its data are coming from api's that are we have created in codeigniter . Now i am trying make this application a pwa . so far,caching of static file and manifes.json are working ,but when it comes to storing those data in IndexedDb and retriving them i am confused how to that.Till now i have find only examples with static json being inserted into IndexedDb ,but i want to know how to store those http response in indexedDb, so that when it goes in offline mode it automatically provide data.Also in every page have more than one http response is coming so it should also provide right data to variables..
If you any part of question than just let me know ,I will try better to explain.
And thank you all in advance.
If the response from api is JSON or some similar sort of data file then you can store in indexDB as string or manipulate as you need.Here's an example of storing JSON as string.
//JSONfile is the response from your api.
var JSONstring = JSON.stringify(JSONfile)
// Storing JSON as string in indexDB
var dbPromise = idb.open('JSON-db', 1, function (upgradeDB) {
var keyValStore = upgradeDB.createObjectStore('JSONs')
keyValStore.put(JSONstring, 'samples')
})
//provide better key name so that you can retrieve it easily from indexDB
Other case if response is some sort of multimedia then you can convert it into blob and then store the blob in indexDB.
return fetch(new Request(prefetchThisUrl, { mode: 'no-cors' }))
.then((resp) => {
resp.blob()
.then((blob) => {
return db.set(prefetchThisUrl, blob);
});
});
You can then get the information from indexDB when required.For a good understanding of storing and retrieving blob from indexDB you can visit this site:https://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/
And for providing right data on your page it's not an issue,you just need to make your logic to respond to request from indexDB.Here's how you can do it.
dbPromise.then(function (db) {
var tx = db.transaction('JSONs')
var keyValStore = tx.objectStore('JSONs')
return keyValStore.get('samples')
}).then(function (val) {
var JSONobject = JSON.parse(val)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With