What is IndexedDB? How does it work?
- Stores data in the browser. It is called the browser database
- More structured than localStorage.
- Used to store objects indexed with a key.
- Can be accessed from the same domain.
- API is asynchronous.
- stores data in key-value pairs.
- Open DB > Create Object Store > On Success, Conduct Transaction > Close Transaction
Let us see a little demo of IndexedDB
- Open console of a Chrome Browser
- Paste the following
const request = indexedDB.open("notes"); request.onupgradeneeded = e => { alert("upgrade"); } request.onsuccess = e => { alert("success"); } request.onerror = e => { alert("error"); }
- This example is something that we created. You will see notes database in Application > IndexedDB > notes
- Another example would be of real IndexedDB used in production
- Open Youtube and see IndexDB in Application tab of developer's console of browser
- You will encounter database named swpushnotificationsdb with a store named swpushnotificationsstore
- Run this example of IndexedDB transaction in the console of your browser
let db; function createDB() { let dbName = "Jokes"; let dbVersion = 5; let request = indexedDB.open(dbName, dbVersion); request.onupgradeneeded = e => { db = e.target.result console.log(db); let jstore = db.createObjectStore("JokeStore", {keyPath: "title"}); let mstore = db.createObjectStore("MockStore", {keyPath: "title"}); alert("upgrade"); } request.onsuccess = e => { db = e.target.result console.log(db); alert("success"); } request.onerror = e => { alert("error"+e.target.error); } } function addRecord(title, text) { let tx = db.transaction("JokeStore","readwrite"); tx.onerror = e => alert(e.target.error); let jstoretx = tx.objectStore("JokeStore"); jstoretx.add({title: title, text: text}); } function viewNotes() { let tx = db.transaction("JokeStore", "readonly"); let jstore = tx.objectStore("JokeStore"); let request = jstore.openCursor(); request.onsuccess = e => { let cursor = e.target.result; if (cursor) { console.log(cursor.key, cursor.value.text); cursor.continue(); } } } createDB(); // Creates db if not there or opens an existing one addRecord("Joke 1", "Knock Knock"); // Adds record addRecord("Joke 2", "Elephant and the ant"); // Adds record viewNotes(); // Displays all records in console
- It connects, creates an entry in the database store, and displays all records on the console.
Comments
Post a Comment