AndyS
AndyS

Reputation: 846

Good practice for indexedDB add then get

I have the code below that inserts a todo object in an indexedDB object store - and then gets a copy of the stored object (see further down) and this works fine.

I'm concerned that I am reusing a transaction that might be unsafe to use - since the transaction has already succeeded.

Should I create another transaction for the get - or is this unnecessary?

    // this is only called after the 'tasks' object store has been opened
    const todoIDB = requestIDB.result
    const transaction = todoIDB.transaction(["tasks"], "readwrite")
    const todoStore = transaction.objectStore("tasks")
    const addRequest = todoStore.add({text:txt_val})
    addRequest.addEventListener("success", ()=>{
      console.log("Added " + "#" + addRequest.result + ": " + txt_val)
      // should I add a new transaction, etc. here?
      const getRequest = todoStore.get(addRequest.result)
      getRequest.addEventListener("success", ()=>{
        console.log("Found " + JSON.stringify(getRequest.result))
      })
    })

Here is some (valid) output (from Chrome):

Added #18: aaa
Found {"text":"aaa","id":18}
Added #19: bbb
Found {"text":"bbb","id":19}

Upvotes: 1

Views: 44

Answers (1)

Joshua Bell
Joshua Bell

Reputation: 8357

Transactions can span multiple requests, so this is fine. (Of course, if the add request fails - e.g. the record already exists - then "success" won't fire the get request won't happen.)

And to clarify a point - when you're observing the "success" event, it's the request that has succeeded, not the transaction. A "complete" or "abort" event will fire at the transaction object when the overall transaction has finished, i.e. when all of the individual requests have succeeded or one has failed and caused the transaction to fail.

Upvotes: 3

Related Questions