Why is db.transaction not working with indexeddb?
Asked Answered
S

3

8

I am new at using inxededdb and am trying to get data out of a store. The store contains data, but for some reason the code stops after trying to set the var tx. If I am missing anything please let me know. Here is the function with which I am trying to get the book:

function getBook(){
    var tx = db.transaction("book", "readonly");
    var store = tx.objectStore("book");
    var index = store.index("by_getid");

    var request = index.get("<?php echo $_GET['book'] ?>");
    request.onsuccess = function() {
      var matching = request.result;
      if (matching !== undefined) {
         document.getElementById("text-container").innerHTML = matching.text;
      } else {
        alert('no match');
        report(null);
      }
    };
}

Solved Version:

function getBook(){
  var db;
  var request = indexedDB.open("library", 1);  

  request.onsuccess = function (evt) {
    db = request.result; 
    var transaction = db.transaction(["book"]);
    var objectStore = transaction.objectStore("book");
    var requesttrans = objectStore.get(<?php echo $_GET['book'] ?>);

    requesttrans.onerror = function(event) {

    };

    requesttrans.onsuccess = function(event) {
      alert(requesttrans.result.text);
    };      
  };
}
Subtangent answered 3/3, 2014 at 13:40 Comment(0)
A
6

The problem is probably your db variable. You are probably accessing a closed or null instance of a connection object.

Try instead to create the db connection right inside the function. Do NOT use a global db variable.

Assurbanipal answered 3/3, 2014 at 17:37 Comment(1)
It worked :) I checked the var db and it was undefined what I did was I reopened the connection in the function :)Subtangent
I
0

index.get yields primary key. You have to get record value using the resulting primary key.

Ineffable answered 3/3, 2014 at 14:11 Comment(2)
i do not think this is the problem i ave put an alert after setting var tx and the alert() never pops up so the code is crashing after setting var tx.Subtangent
OK. you got bigger problem. better getting start with my library, ydn-db.Ineffable
M
0

I has problem with transaction, it's return error db.transaction is not a function or return undefined. You will try like this, it's working for me:

const table = transaction.objectStore('list');
const query = table.getAll();
query.onsuccess = () => {
  const list = query?.result;
  console.log(list);
};
Meister answered 5/12, 2022 at 15:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.