Veri ekleme ve okuma
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
-
Transaction parçalarını eşleştir
- 'readonly'
- yalnızca okuma
- 'readwrite'
- okuma ve yazma
- objectStore()
- store'u al
- transaction()
- işlem başlat
-
Store'a yeni kayıt ekle
store.____({ id: 1, text: 'Merhaba' });Cevabı göster
store.add({ id: 1, text: 'Merhaba' }); -
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.