files/en-us/web/api/idbdatabase/transaction/index.md
{{ APIRef("IndexedDB") }} {{AvailableInWorkers}}
The transaction method of the {{domxref("IDBDatabase")}} interface immediately returns a transaction object ({{domxref("IDBTransaction")}}) containing the {{domxref("IDBTransaction.objectStore")}} method, which you can use to access your object store.
transaction(storeNames)
transaction(storeNames, mode)
transaction(storeNames, mode, options)
storeNames
: The names of object stores that are in the scope of the new transaction, declared as an array of strings. Specify only the object stores that you need to access. If you need to access only one object store, you can specify its name as a string. Therefore the following lines are equivalent:
db.transaction(["my-store-name"]);
db.transaction("my-store-name");
If you need to access all object stores in the database, you can use the property {{domxref("IDBDatabase.objectStoreNames")}}:
const transaction = db.transaction(db.objectStoreNames);
Passing an empty array will throw an exception.
mode {{optional_inline}}
readonly
readwrite
readwriteflush {{non-standard_inline}} {{experimental_inline}}
complete event.
This might be used for storing critical data that cannot be recomputed later.options {{optional_inline}}
durability
"strict"
relaxed)."relaxed"
strict, and is recommended for ephemeral data such as caches or quickly changing records."default"
An {{domxref("IDBTransaction")}} object.
InvalidStateError {{domxref("DOMException")}}
NotFoundError {{domxref("DOMException")}}
mode parameter is invalid.InvalidAccessError {{domxref("DOMException")}}
In this example we open a database connection, then use transaction() to open a transaction on the database. For a complete example, see our To-do Notifications app (view example live).
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Database initialized.";
// store the result of opening the database in the db variable.
// This is used a lot below
db = DBOpenRequest.result;
// Run the displayData() function to populate the task list with
// all the to-do list data already in the IDB
displayData();
};
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction completed: database modification finished.";
};
transaction.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction not opened due to error. Duplicate items not allowed.";
};
// you would then go on to do something to this database
// via an object store
const objectStore = transaction.objectStore("toDoList");
// etc.
{{Specifications}}
{{Compat}}