CodeBlanks Logo Icon CodeBlanks

Veri ekleme ve okuma

JavaScript kursu · İleri seviye · Ders 87/100

Bir transaction üzerinden veri ekleyip getirmeyi öğrenirsin.

Transaction nedir?

IndexedDB'de her okuma ve yazma işlemi bir transaction (işlem) içinde yapılır. db.transaction(storeName, mode) çağrısıyla başlatırsın. mode ya 'readonly' ya da 'readwrite' olur.

const tx = db.transaction('notes', 'readwrite');

Transaction, store üzerinde tutarlı bir ortam sağlar; hata olursa tüm değişiklikler geri alınır. İşin bitince transaction otomatik olarak kapanır.

Veri eklemek ve okumak

Transaction üzerinden objectStore('notes') ile store'u alır, sonra store.add(obj) ile yeni kayıt eklersin. Kaydı okumak için store.get(key) kullanırsın.

const store = tx.objectStore('notes');
store.add({ id: 1, text: 'Merhaba' });

Her iki çağrı da bir IDBRequest döndürür; sonucu request.onsuccess ile alırsın. Aynı anahtara add yapılırsa hata fırlatılır; üzerine yazmak için put kullanılır.

Uygulama Bir notu transaction ile ekle

db.transaction ile 'notes' store'u üzerinde 'readwrite' erişimi al ve tx değişkenine ata. tx.objectStore('notes')'u store değişkenine al. store.add ile { id: 1, text: 'Hello' } nesnesini ekle.

Örnek çözümü göster
const tx = db.transaction('notes', 'readwrite');
const store = tx.objectStore('notes');
store.add({ id: 1, text: 'Hello' });

Kendini test et

  1. Transaction parçalarını eşleştir

    'readonly'
    yalnızca okuma
    'readwrite'
    okuma ve yazma
    objectStore()
    store'u al
    transaction()
    işlem başlat
  2. Store'a yeni kayıt ekle

    store.____({ id: 1, text: 'Merhaba' });
    Cevabı göster
    store.add({ id: 1, text: 'Merhaba' });
  3. Veri eklemek için hangi mod kullanılır?

    • 'readonly'
    • 'readwrite'
    • 'writeonly'
    • 'add'
    Cevabı göster

    'readwrite' — Doğru! 'readwrite' transaction içinde add ve put yapabilirsin.

İleri seviye bölümündeki tüm dersler