I am utilizing the indexedDB Promised library to convert the indexedDB API into promises.
It seems that once my fetch operation is completed, my indexed db transaction becomes inactive. Could it be timing out?
The error message I am encountering is:
DOMException: Failed to execute 'delete' on 'IDBCursor': The transaction has finished.
My goal is to delete an item from indexedDB
only if the fetch operation is successful. I understand that I could create a new transaction after the fetch to retrieve and remove the item. However, I am curious if there is a more efficient way to achieve this without initiating a new transaction. Am I overlooking something?
Can someone shed light on why this issue is occurring?
DBHelper.DBPromised.then( db => {
const store = db.transaction('deferredReviews', 'readwrite').objectStore('deferredReviews');
const submittedRes = {};
store.openCursor()
.then(function submitAndDelete(cursor) {
if (!cursor) return;
console.log(cursor.value);
fetch(`${DBHelper.DATABASE_URL}/reviews`, {
method: 'POST',
body: JSON.stringify({
restaurant_id: cursor.value.restaurant_id,
name: cursor.value.name,
createdAt: cursor.value.deferredAt,
rating: cursor.value.rating,
comments: cursor.value.comments
})
})
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json();
})
// If response is ok then delete from indexedDB.
.then(review => {
if (!review) return new Error('Could not submit');
if (cursor.value.restaurant_name in submittedRes) {
submittedRes[cursor.value.restaurant_name] = submittedRes[cursor.value.restaurant_name] + 1;
} else {
submittedRes[cursor.value.restaurant_name] = 1;
}
cursor.delete();
return cursor.continue().then(submitAndDelete);
});
})
.then(() => {
if (Object.keys(submittedRes).length === 0 && submittedRes.constructor === Object) return;
DBHelper.showDeferredSubmitModal(submittedRes);
});
});