JSFiddle - React, Tailwind, and code Playground

by Dan Shahin

HTML

<button id="query">query</button>
<button id="put">put</button>
<div id="results"></div>
<input type="text" id="term"></input>

JavaScript

var request = indexedDB.open("library4");
var db;
request.onupgradeneeded = function() {
    console.log('needed');
  // The database did not previously exist, so create object stores and indexes.
  var db = request.result;
  var store = db.createObjectStore("books", {keyPath: "isbn"});
  var titleIndex = store.createIndex("by_title", "title", {unique: true});
  var authorIndex = store.createIndex("by_author", "author");

  // Populate with initial data.
  store.put({title: "Quarry Memories", author: "Fred", isbn: 123456});
  store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567});
  store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678});

};

request.onsuccess = function() {
      db = request.result;
    console.log('success', db);
    
};


$('#query').on('click',function(){
    var tx = db.transaction("books", "readonly");
    var store = tx.objectStore("books");
    var index = store.index("by_title");
    var term = $('#term').val();
    console.log('term',term);
    
    var request = index.get(term);
    request.onsuccess = function() {
        var matching = request.result;
        if (matching !== undefined) {
            // A match was found.
            console.log(matching.isbn, matching.title, matching.author);
        } else {
            // No match was found.
            console.log(null);
        }
    }; 

});


$('#put').on('click',function(){
    alert('put');
    var tx = db.transaction("books", "readwrite");
    var store = tx.objectStore("books");
    
    store.put({title: "New", author: "Fred", isbn: 99888});
    store.put({title: "Newer", author: "Fred", isbn: 666666});
    store.put({title: "newest", author: "Barney", isbn: 7777777});
    
    tx.oncomplete = function() {
      // All requests have succeeded and the transaction has committed.
        console.log('all done');
    };
});