objectStore.add not adding data with different key in IndexedDb

815 Views Asked by At

I'd like to have a button that collects values from three entry fields, passes them to a javascript function, which in turn makes them into a single object and enters them into IndexedDb database objectStore. I've got it to enter the first three values as an object, but on subsequent onclicks, it passes them to function, but will not add them to database.

function callIdb(entry1, entry2, entry3) {

    document.getElementById('registernewsletter').innerHTML = 'Check ' + entry1 + ' for New User Offer!';
    var nameI = entry1
    var ageI = entry2;
    var emailI = entry3;

    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction || {READ_WRITE: "readwrite"}; // This line should only be needed if it is needed to support the object's constants for older browsers
    window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;

    if (!window.indexedDB) {
        console.log("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.");
        } else { 
        console.log("You're good to go with IndexedDB");
        };

    var request = window.indexedDB.open("restaurantDatabase", 1);
    request.onerror = function(event) {
        console.log("Hi, YouFail.  PleaseTry again", event);
        };


    var restaurantData = [];
    var b = (function () {
      var c = [];
      return function () {
        c.push({name: nameI, age: ageI, email: emailI});
        return c;
        }
    })();

    var d = b();
    console.log(d);
    console.log("New data: ", d, d.isArray);
    d.forEach(function(rest) {
        console.log("I: ", d);
        });

    request.onupgradeneeded = function(event) {
        console.log('win upgrade');
        var db = event.target.result;
        console.log("OnUpgrade:  db= ", db);

        var oS = db.createObjectStore("restaurants", { keyPath: "email" });
        oS.createIndex("name", "name", { unique: false });
        oS.createIndex("email", "email", { unique: true });
        oS.createIndex("age", "age", { unique: false });

        oS.transaction.oncomplete = function(event) {
            var rTrans = db.transaction("restaurants", "readwrite").objectStore("restaurants");

            d.forEach(function(restaurant) {
                rTrans.add(restaurant);
                console.log("You followed directions! gd jb", restaurant, "stored in ", rTrans);
            });
        };
    };
    request.onupgradeneeded.onerror = function(event) {
        console.log("err", event);
    }
}

Should I take the add out of onupgradeneeded? I thought all edits to db had to be inside this event.

    <form id="newsletter_form" class="newsletter_form">
        <input type="text" id="idbentry1" class="newsletter_input" placeholder="Restuarant Name" required="required">
        <input type="text" id="idbentry2" class="newsletter_input" placeholder="Years at Location">
        <input type="email" id="idbentry3" class="newsletter_input" placeholder="email">

Insert Values into IndexedDb()

Here's first entry acting nicely:

You're good to go with IndexedDB
rapidapp.js:198 [{…}]
rapidapp.js:199 New data:  [{…}] undefined
rapidapp.js:201 I:  [{…}]
rapidapp.js:212 win upgrade
rapidapp.js:214 OnUpgrade:  db=  IDBDatabase {name: "restaurantDatabase", version: 1, objectStoreNames: DOMStringList, onabort: null, onclose: null, …}
rapidapp.js:229 You followed directions! gd jb {name: "ert", age: "ww", email: "tt"} stored in  IDBObjectStore {name: "restaurants", keyPath: "email", indexNames: DOMStringList, transaction: IDBTransaction, autoIncrement: false}

And here's the second entry stopping before onupgradeneeded.

You're good to go with IndexedDB
rapidapp.js:198 [{…}]
rapidapp.js:199 New data:  [{…}] undefined
rapidapp.js:201 I:  [{…}]
1

There are 1 best solutions below

0
peer On BEST ANSWER

Finally got it:

function callIdb(entry1, entry2, entry3) {

    document.getElementById('registernewsletter').innerHTML = 'Check ' + entry1 + ' for New User Offer!';
    var nameI = entry1
    var ageI = entry2;
    var emailI = entry3;

    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction || {READ_WRITE: "readwrite"}; // This line should only be needed if it is needed to support the object's constants for older browsers
    window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;

    if (!window.indexedDB) {
        console.log("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.");
        } else { 
        console.log("You're good to go with IndexedDB");
        };

    var request = window.indexedDB.open("restaurantDatabase", 1);

    var b = (function () {
      var c = [];
      return function () {
        c.push({name: nameI, age: ageI, email: emailI});
        return c;
        }
    })();

    request.onerror = function(event) {
        console.log("Hi, YouFail.  PleaseTry again", event);
        };

    var d = b();
    console.log(d);
    console.log("New data: ", d, d.isArray);
    d.forEach(function(rest) {
        console.log("I: ", d);
        });

    request.onupgradeneeded = function(event) {
        console.log('(WINR.UGN)Within request.upgradeneeded');

        var db = event.target.result;
        console.log("(WINR.UGN) db:", db);

        var oS = db.createObjectStore("restaurants", { keyPath: "email" });

        oS.createIndex("name", "name", { unique: false });
        oS.createIndex("email", "email", { unique: true });
        oS.createIndex("age", "age", { unique: false });  
        };

    request.onsuccess = function(event) {
        console.log('(WOR.NS) Within request.onsuccess');
        var db = event.target.result;
        console.log("(WOR.NS) db= ", db);

        var rTrans = db.transaction("restaurants", "readwrite").objectStore("restaurants"); 

        d.forEach(function(restaurant) {
            rTrans.add(restaurant);
            console.log("You followed directions! Well done. var restaurant: ", restaurant, "stored with this transaction: ", rTrans);
            });

        rTrans.oncomplete = function () {
            console.log("CONGRATULATIONS FOOLS.");
            }
        };

    request.onupgradeneeded.onerror = function(event) {
        console.log("err", event);
        }
    }
  1. Open database outside of all handlers (var request in example).
  2. Declare variables (i.e. - user input etc..) outside handlers.
  3. request.onupgradeneeded handler with function creates objectStore and indices and then that function is done and the...
  4. request.onsuccess handler is in play. This is where you open transaction and add data.
  5. Use error handlers!

Also, this ref was the most helpful at this point in the process: https://www.w3.org/TR/IndexedDB/#dom-idbtransactionmode-readwrite.

Thanks, Peer