My journey to explore various web technologies (such as HTML, CSS, JavaScript) led me to create a simple web application. To enhance the functionality of my app, I integrated IndexedDB for data storage and operations like insert, update, get and delete.
However, a significant issue arises when I close or reload the browser tab - the database disappears along with all the stored data. Is there a method to retain this data even when the browser is closed?
The initialization of IndexedDB in the code snippet below:
let db = null;
function create_db(nameDB, stores) {
const request = window.indexedDB.open(nameDB, 1);
request.onerror = function(event) {
console.log("Problem opening DB.")
}
request.onupgradeneeded = function(event) {
db = event.target.result;
const store = db.createObjectStore(stores, {keyPath: 'id'});
store.transaction.oncomplete = function(event) {
console.log("Persons store successfully completed;")
}
}
request.onsuccess = function(event) {
db = event.target.result;
console.log("Successfully opened DB.")
insert_record(nameStorePersons, persons);
}
}
Edit:
The function used to add records:
function insert_record(nameStore, records) {
if (db) {
const insert_transaction = db.transaction(nameStore, 'readwrite');
const store = insert_transaction.objectStore(nameStore);
insert_transaction.onerror = function () {
console.log("Problem with transactions.");
}
insert_transaction.oncomplete = function () {
console.log("All transactions complete.");
}
records.forEach(record => {
let request = store.add(record);
request.onerror = function(event) {
console.log("Could not add: ", record);
}
request.onsuccess = function(event) {
console.log("Successfully added: ", record);
}
});
}
}
Database name and store details:
const nameOfDB = 'LocalDB';
const nameStorePersons = 'persons';
An illustration of the inserted data:
const persons = [
{
"id" : "d1",
"filename" : "documents/d1.pdf",
"status" : "Pending"
},
{
"id" : "d2",
"filename" : "documents/d2.pdf",
"status" : "Testing"
}]