12/08/2018, 16:23

Hướng dẫn sử dụng IndexedDB cơ bản

Khái niệm: IndexedDB là một dạng kho lưu trữ dữ liệu ở phía trình duyệt người dùng (tương tự local storage, session storage hay cookie). Thường được sử dụng để lưu trữ dữ liệu lớn và thực hiện các thao tác tìm kiếm với hiệu năng cao tại chính trình duyệt. Đặc điểm: Lưu trữ dưới dạng key-value ...

  • Khái niệm: IndexedDB là một dạng kho lưu trữ dữ liệu ở phía trình duyệt người dùng (tương tự local storage, session storage hay cookie). Thường được sử dụng để lưu trữ dữ liệu lớn và thực hiện các thao tác tìm kiếm với hiệu năng cao tại chính trình duyệt.
  • Đặc điểm:
    • Lưu trữ dưới dạng key-value
    • Không phải cơ sở dữ liệu quan hệ
    • Không phải là SQL
    • API async
    • Hỗ trợ truy xuất các DB có cùng domain
    • Đã có 94.13% trình duyệt hỗ trợ. Chi tiết xem tại đây: http://caniuse.com/#feat=indexeddb
    • Có thể lưu trữ như temporary storage hoặc persistent storage

1. Mở kết nối

var request = window.indexedDB.open(dbName, 1)
var db = null;

Lần đầu kết nối chúng ta phải init objectStore cho DB. Ví dụ:

request.onupgradeneeded = (event) => {
    db = event.target.result
    db.createObjectStore(collectionName, {
        // Giá trị cột key tự động tăng
        autoIncrement: true
    })
}

2. Thêm dữ liệu

Các câu lệnh CURD ta đều phải thực hiện qua transaction. Default mode là readonly. Muốn sửa xóa thì ta phải dùng readwrite

db.transaction(collection, "readwrite")
.objectStore(collectionName)
.add(value)

3. Đọc dữ liệu

var request = db.transaction(collectionName).objectStore(collectionName).get(key)

request.onsuccess = (event) => {
    console.log(`Value is: ${event.target.result}` )
}

4. Sửa dữ liệu

var objectStore = this.db.transaction(collectionName, 'readwrite').objectStore(collectionName)
var request = objectStore.get(key)

request.onsuccess = (event) => {
    var data = event.target.result
    // Cập nhật giá trị mới
    data.someAttr = true
    // Lưu vào DB
    objectStore.put(data, key)
 }

5. Xóa dữ liệu

 db.transaction(collectionName, "readwrite").objectStore(collectionName).delete(key)
  • Mình đã comment trong code khá đầy đủ rồi. Các bạn có thể tham khảo
  • Kết quả khi bật F12 - Application - IndexedDB - Chúc các bạn thành công!             </div>
            
            <div class=
0