I’m trying to get my app to use indexedDB when there is no internet connection. I have an idb.js file that sets up the object store and then defines a saveRecord function that I use in another js file:
let db;
const request = indexedDB.open('pizza_hunt', 1);
request.onupgradeneeded = function(event) {
const db = event.target.result;
db.createObjectStore('new_pizza', { autoIncrement: true });
}
request.onsuccess = function(event) {
// when db is successfully created with its object store (from onupgradeneeded event above) or simply established a connection, save reference to db in global variable
if (navigator.onLine) {
// uploadPizza();
}
};
request.onerror = function(event) {
console.log(event.target.errorCode);
};
// This function will be executed if we attempt to submit a new pizza and there's no internet connection
function saveRecord(record) {
const transaction = db.transaction(['new_pizza'],'readwrite');
const pizzaObjectStore = transaction.objectStore('new_pizza');
pizzaObjectStore.add(record);
};
But when the function is called in the other file, I keep getting the error from above, that .transaction is undefined and it doesn’t write anything to the new_pizza object store.
Here’s the context in which it is called (another js file). It all works unless the catch is triggered:
const formData = { pizzaName, createdBy, size, toppings };
fetch('/api/pizzas', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => response.json())
.then(postResponse => {
alert('Pizza created succesfully!');
console.log(postResponse);
})
.catch(err => {
console.log(err);
saveRecord(formData);
});