DEV Community

Roby Cigar
Roby Cigar

Posted on • Edited on

indexed db

// Open or create the IndexedDB database
const request = indexedDB.open('todo', 1);

// Handle database upgrade or creation
request.onupgradeneeded = function (event) {
  const db = event.target.result;

  // Create an object store
  const objectStore = db.createObjectStore('tasks', { keyPath: 'id', autoIncrement: true });

  // Create an index
  objectStore.createIndex('taskName', 'taskName', { unique: false });
};

// Handle successful database opening
request.onsuccess = function (event) {
  const db = event.target.result;

  // Perform database operations here
  // For example, you can add, delete, or retrieve data

  // Close the database connection (optional)
  db.close();
};

// Handle database opening errors
request.onerror = function (event) {
  console.error('IndexedDB error:', event.target.error);
};
Enter fullscreen mode Exit fullscreen mode
// Open or create the IndexedDB database
const request = indexedDB.open('todo', 1);

// Handle database upgrade or creation
request.onupgradeneeded = function (event) {
  const db = event.target.result;

  // Create an object store
  const objectStore = db.createObjectStore('tasks', { keyPath: 'id', autoIncrement: true });

  // Create an index
  objectStore.createIndex('taskName', 'taskName', { unique: false });
};

// Handle successful database opening
request.onsuccess = function (event) {
  const db = event.target.result;

  // Start a transaction and get the object store
  const transaction = db.transaction(['tasks'], 'readwrite');
  const objectStore = transaction.objectStore('tasks');

  // Create a new task object
  const newTask = { taskName: 'Task 1', priority: 'High', completed: false };

  // Add the new task to the object store
  const requestAdd = objectStore.add(newTask);

  // Handle successful task addition
  requestAdd.onsuccess = function (event) {
    console.log('Task added successfully');
  };

  // Handle task addition errors
  requestAdd.onerror = function (event) {
    console.error('Error adding task:', event.target.error);
  };

  // Complete the transaction
  transaction.oncomplete = function () {
    // Close the database connection (optional)
    db.close();
  };
};

// Handle database opening errors
request.onerror = function (event) {
  console.error('IndexedDB error:', event.target.error);
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)