localForage - Improved offline storage

Posted by n00b Saibot on Mon, 08 Nov 2021 23:12:05 +0100

1. What is localForage

localForage is a JavaScript library that is similar in simplicity   localStorage   Asynchronous storage of API s to improve the offline experience of your Web applications. It can store many types of data, not just strings.

localForage has an elegant downgrade policy, and if your browser does not support IndexedDB or WebSQL, use localStorage. Available in all major browsers: Chrome, Firefox, IE, and Safari Mobile.

localForage provides callback API s as well as support   ES6 Promises API You can choose.

2. Install using localForage

Using localForage, please   Download the latest version   Or use   npm (npm install localforage) or   bower (bower install localforage) to install.

Then, just include the JS file to use localForage:<script src="localforage.js"></script>. You don't need to run any initialization methods or wait   onready   Event.

# Install via npm:
npm install localforage

# Or via bower:
bower install localforage
<script src="localforage.js"></script>
<script>console.log('localforage is: ', localforage);</script>

3. Use of localForage

GETITEM

localforage.getItem('somekey').then(function(value) {
    // This code runs when values in the offline repository are loaded
    console.log(value);
}).catch(function(err) {
    // When an error occurs, the code runs here
    console.log(err);
});

// Callback version:
localforage.getItem('somekey', function(err, value) {
    // This code runs when values in the offline repository are loaded
    console.log(value);
});

getItem(key, successCallback)

Get the value of the key from the repository and provide the result to the callback function. getItem() if key does not exist   Will return   null.

  When Stored   undefined   When,   getItem()   Will also return   null. Because   localStorage restrictions And localForage cannot be stored for compatibility reasons   undefined.

SETITEM

localforage.setItem('somekey', 'some value').then(function (value) {
    // When the value is stored, other operations can be performed
    console.log(value);
}).catch(function(err) {
    // When an error occurs, the code runs here
    console.log(err);
});

// Unlike localStorage, you can store non-string types
localforage.setItem('my array', [1, 2, 'three']).then(function(value) {
    // Output as follows`1`
    console.log(value[0]);
}).catch(function(err) {
    // When an error occurs, the code runs here
    console.log(err);
});

// You can even store the binary data returned by the AJAX response
req = new XMLHttpRequest();
req.open('GET', '/photo.jpg', true);
req.responseType = 'arraybuffer';

req.addEventListener('readystatechange', function() {
    if (req.readyState === 4) { // readyState Complete
        localforage.setItem('photo', req.response).then(function(image) {
            // The following is a blob URI for a legal <img>tag
            var blob = new Blob([image]);
            var imageURI = window.URL.createObjectURL(blob);
        }).catch(function(err) {
          // When an error occurs, the code runs here
          console.log(err);
        });
    }
});

setItem(key, value, successCallback)

Save data to an offline warehouse. You can store the following types of JavaScript objects:

  • Array
  • ArrayBuffer
  • Blob
  • Float32Array
  • Float64Array
  • Int8Array
  • Int16Array
  • Int32Array
  • Number
  • Object
  • Uint8Array
  • Uint8ClampedArray
  • Uint16Array
  • Uint32Array
  • String

  When using localStorage and WebSQL as backends, binary data is serialized before being saved (and retrieved). Serialization results in increased size when saving binary data.

Example

REMOVEITEM

localforage.removeItem('somekey').then(function() {
    // When the value is removed, the code runs here
    console.log('Key is cleared!');
}).catch(function(err) {
    // When an error occurs, the code runs here
    console.log(err);
});

removeItem(key, successCallback)

Delete the value corresponding to the key from the offline repository.

Example

CLEAR

localforage.clear().then(function() {
    // When the database is completely deleted, the code runs here
    console.log('Database is now empty.');
}).catch(function(err) {
    // When an error occurs, the code runs here
    console.log(err);
});

clear(successCallback)

Remove all key s from the database and reset the database.

localforage.clear()   All values in the offline warehouse will be deleted. Use this method with caution.

LENGTH

localforage.length().then(function(numberOfKeys) {
    // Size of output database
    console.log(numberOfKeys);
}).catch(function(err) {
    // When an error occurs, the code runs here
    console.log(err);
});

length(successCallback)

Gets the number of key s in the offline warehouse (that is, the "length" of the data warehouse).

KEY

localforage.key(2).then(function(keyName) {
    // Keyname
    console.log(keyName);
}).catch(function(err) {
    // When an error occurs, the code runs here
    console.log(err);
});

key(keyIndex, successCallback)

Get its name from the key's index

  Although it's a continuation of the localStorage API, this approach is considered a bit bizarre.

KEYS

localforage.keys().then(function(keys) {
    // Array containing all key names
    console.log(keys);
}).catch(function(err) {
    // When an error occurs, the code runs here
    console.log(err);
});

keys(successCallback)

Get all key s in the data warehouse.

ITERATE

// Same code, but using ES6 Promises
localforage.iterate(function(value, key, iterationNumber) {
    // This callback function will run on all key/value pairs
    console.log([key, value]);
}).then(function() {
    console.log('Iteration has completed');
}).catch(function(err) {
    // When an error occurs, the code runs here
    console.log(err);
});

// Exit iteration early:
localforage.iterate(function(value, key, iterationNumber) {
    if (iterationNumber < 3) {
        console.log([key, value]);
    } else {
        return [key, value];
    }
}).then(function(result) {
    console.log('Iteration has completed, last iterated pair:');
    console.log(result);
}).catch(function(err) {
    // When an error occurs, the code runs here
    console.log(err);
});

iterate(iteratorCallback, successCallback)

Iterate over all value/key key key pairs in the data warehouse.

Iterator Callback   Each key-value pair is called once with the following parameters: 1. value is value 2. key is key name 3. iterationNumber is iteration index-number

  By   Iterator Callback   Returns a non in a callback function   undefined   Value of, can quit ahead of time   iterate. Iterator Callback   The return value of the is the result of the entire iteration and is passed in   successCallback.

This means that if you are using CoffeeScript, then you need to manually execute an empty   return   Statement to continue iterating over all key/value pairs.

Topics: Javascript Front-end chrome