LocalForage là gì

LocalForage là một thư viện Javascript giúp cải thiện các trải nghiệm offline, nó thực chất là Web Storage API( localStorage và sessionStorage) được mở rộng với value hỗ trợ nhiều kiểu dữ liệu hơn, bao gồm: Array, ArrayBuffer, Blob, Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Number, Object, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, String

Cơ chế hoạt động cơ bản

Download: localforage.min.js

Cài đặt: 

# Install via npm:
npm install localforage

# Or, with yarn:
yarn add localforage

<script src="localforage.js"></script>
<script>console.log('localforage is: ', localforage);</script>
To use localForage, download the latest release or install with npm (npm install localforage) or yarn (yarn add localforage).

Sử dụng:

GETITEM: getItem(key, successCallback)

localforage.getItem('somekey').then(function(value) {
    // This code runs once the value has been loaded
    // from the offline store.
    console.log(value);
}).catch(function(err) {
    // This code runs if there were any errors
    console.log(err);
});

// Callback version:
localforage.getItem('somekey', function(err, value) {
    // Run this code once the value has been
    // loaded from the offline store.
    console.log(value);
});

Or, use `async`/`await`:

```js
try {
    const value = await localforage.getItem('somekey');
    // This code runs once the value has been loaded
    // from the offline store.
    console.log(value);
} catch (err) {
    // This code runs if there were any errors.
    console.log(err);
}

SETITEM : setItem(key, value, successCallback)

localforage.setItem('somekey', 'some value').then(function (value) {
    // Do other things once the value has been saved.
    console.log(value);
}).catch(function(err) {
    // This code runs if there were any errors
    console.log(err);
});

// Unlike localStorage, you can store non-strings.
localforage.setItem('my array', [1, 2, 'three']).then(function(value) {
    // This will output `1`.
    console.log(value[0]);
}).catch(function(err) {
    // This code runs if there were any errors
    console.log(err);
});

// You can even store binary data from an AJAX request.
req = new XMLHttpRequest();
req.open('GET', '/photo.jpg', true);
req.responseType = 'arraybuffer';

req.addEventListener('readystatechange', function() {
    if (req.readyState === 4) { // readyState DONE
        localforage.setItem('photo', req.response).then(function(image) {
            // This will be a valid blob URI for an <img> tag.
            var blob = new Blob([image]);
            var imageURI = window.URL.createObjectURL(blob);
        }).catch(function(err) {
          // This code runs if there were any errors
          console.log(err);
        });
    }
});

REMOVEITEM: removeItem(key, successCallback)

localforage.removeItem('somekey').then(function() {
    // Run this code once the key has been removed.
    console.log('Key is cleared!');
}).catch(function(err) {
    // This code runs if there were any errors
    console.log(err);
});

Ứng dụng LocalForage

  • Lưu trữ các giá trị khi truy vấn từ db mà không cần phải gọi lại nhiều lần

Vd: lưu các giá trị phân trang mà không phải gọi lại db nhiều lần, lưu các kết quả truy vấn lọc (tìm kiếm bất động sản: tỉnh thành, dự án, diện tích… )

Tài liệu tham khảo

https://localforage.github.io/localForage

Bài viết liên quan

post-no-image

Những bài viết hay về lập trình javascript

post-no-image

Một số bài tập Javascript hay P.1