JavaScript
Özet - IndexedDB
IndexedDB kullanarak bir not uygulamasının verilerini kalıcı saklayan bir uygulama yazarsın.
Özet - IndexedDB akışı
Bir IndexedDB akışı dört adımdan oluşur: aç, yapı oluştur, işlem yap, sonucu al. Önce indexedDB.open ile veritabanını açarsın; onupgradeneeded içinde store ve indeksleri oluşturursun.
Sonra db.transaction ile bir işlem başlatır, objectStore üzerinden add, get ya da getAll yaparsın. Sonucu request.onsuccess ile alırsın.
Uygulama NotesDB'yi aç, store'u ve notu ekle
indexedDB.open ile 'NotesDB' veritabanını sürüm 1 ile aç ve request değişkenine ata. request.onupgradeneeded içinde event.target.result'i db'ye al ve 'notes' store'unu { keyPath: 'id' } ile oluştur. request.onsuccess içinde event.target.result'i db'ye al, 'readwrite' transaction aç, objectStore('notes')'u al ve { id: 1, text: 'First note' } nesnesini add ile ekle.
Örnek çözümü göster
const request = indexedDB.open('NotesDB', 1);
request.onupgradeneeded = function(event) {
const db = event.target.result;
db.createObjectStore('notes', { keyPath: 'id' });
};
request.onsuccess = function(event) {
const db = event.target.result;
const tx = db.transaction('notes', 'readwrite');
const store = tx.objectStore('notes');
store.add({ id: 1, text: 'First note' });
};
Özet - temel noktalar
IndexedDB'nin önemli noktaları: asenkron API, transaction tabanlı erişim, object store ile kayıt kümeleri, keyPath ile anahtar alanı ve indeks ile hızlı arama. Yapı değişiklikleri yalnızca onupgradeneeded içinde yapılır.
Veriler tarayıcıda kalıcıdır; büyük nesneler ve dosyalar bile tutulabilir. console.log ile ara değerleri yazdırarak akışı izleyebilirsin.
Uygulama Tüm notları çek
db.transaction ile 'notes' store'u üzerinde 'readonly' erişimi al ve tx değişkenine ata. tx.objectStore('notes').getAll() çağrısını request değişkenine ata. request.onsuccess içinde console.log ile request.result'u yazdır.
Örnek çözümü göster
const tx = db.transaction('notes', 'readonly');
const request = tx.objectStore('notes').getAll();
request.onsuccess = function(event) {
console.log(request.result);
};
Kendini test et
-
Bir kaydın üzerine yazmak için hangisi kullanılır?
- store.put
- store.add
- store.set
- store.update
Cevabı göster
store.put — Doğru! store.put mevcut kaydın üzerine yazar; yoksa ekler.
-
IndexedDB akışını eşleştir
- indexedDB.open
- veritabanını aç
- onupgradeneeded
- yapıyı oluştur
- db.transaction
- işlem başlat
- store.add
- kayıt ekle
- request.onsuccess
- sonucu al
Sıradaki ders: MutationObserver