To start working with IndexedDB, we first need to open (connect to) a database. The first step in opening an IndexedDB database is using window.indexedDB in conjunction with the open method. The open method has two parameters: the database name (required, string type), and version 1 by default (optional, positive integer).
The call returns the declared object; we should listen to events on the opening request. The events include success, error, and upgradeneeded. Success means that the database is ready with an accessible database object, and the apparent error event means that the database has failed to open. The upgradeneeded handler triggers when the database does not yet exist (technically, its version is 0), so we can perform the initialization.
Code Example :Syntax : indexedDB.open(name, version);
let openRequest = indexedDB.open('store', 1);
openRequest.onupgradeneeded = function () {
// triggers if the client had no database
// ...perform initialization...
};
openRequest.onerror = function () {
console.error('Error', openRequest.error);
};
openRequest.onsuccess = function () {
let db = openRequest.result;
// continue working with database using db object
};?