### Installing localForage Source: https://localforage.github.io/localForage Commands for adding the library to a project using package managers. ```bash # Install via npm: npm install localforage # Or, with yarn: yarn add localforage ``` -------------------------------- ### keys Source: https://localforage.github.io/localForage Get the list of all keys in the datastore. ```APIDOC ## keys(successCallback) ### Description Get the list of all keys in the datastore. ### Usage ```javascript localforage.keys().then(function(keys) { console.log(keys); }).catch(function(err) { console.log(err); }); ``` ``` -------------------------------- ### Including localForage via script tag Source: https://localforage.github.io/localForage Example of loading the library directly in an HTML file. ```html ``` -------------------------------- ### length Source: https://localforage.github.io/localForage Gets the number of keys in the offline store. ```APIDOC ## length(successCallback) ### Description Gets the number of keys in the offline store (i.e. its “length”). ### Usage ```javascript localforage.length().then(function(numberOfKeys) { console.log(numberOfKeys); }).catch(function(err) { console.log(err); }); ``` ``` -------------------------------- ### Get all keys in localForage Source: https://localforage.github.io/localForage Retrieves an array containing all key names present in the datastore. ```javascript localforage.keys().then(function(keys) { // An array of all the key names. console.log(keys); }).catch(function(err) { // This code runs if there were any errors console.log(err); }); ``` -------------------------------- ### key Source: https://localforage.github.io/localForage Get the name of a key based on its ID. ```APIDOC ## key(keyIndex, successCallback) ### Description Get the name of a key based on its ID. ### Usage ```javascript localforage.key(2).then(function(keyName) { console.log(keyName); }).catch(function(err) { console.log(err); }); ``` ``` -------------------------------- ### Get current driver name Source: https://localforage.github.io/localForage Retrieve the name of the currently active storage driver. ```javascript localforage.driver(); // "asyncStorage" ``` -------------------------------- ### Get a key name by index Source: https://localforage.github.io/localForage Retrieves the name of a key based on its numerical ID. ```javascript localforage.key(2).then(function(keyName) { // Name of the key. console.log(keyName); }).catch(function(err) { // This code runs if there were any errors console.log(err); }); ``` -------------------------------- ### Get the number of keys in localForage Source: https://localforage.github.io/localForage Retrieves the total count of keys currently stored in the offline store. ```javascript localforage.length().then(function(numberOfKeys) { // Outputs the length of the database. console.log(numberOfKeys); }).catch(function(err) { // This code runs if there were any errors console.log(err); }); ``` -------------------------------- ### ready Source: https://localforage.github.io/localForage Returns a promise that resolves when the driver initialization process is complete. ```APIDOC ## ready() ### Description Determines if the asynchronous driver initialization process has finished. Useful for confirming which driver has been selected. ``` -------------------------------- ### Wait for driver initialization Source: https://localforage.github.io/localForage Use ready() to execute code only after the storage driver has finished initializing. ```javascript localforage.ready().then(function() { // This code runs once localforage // has fully initialized the selected driver. console.log(localforage.driver()); // LocalStorage }).catch(function (e) { console.log(e); // `No available storage method found.` // One of the cases that `ready()` rejects, // is when no usable storage driver is found }); ``` -------------------------------- ### Create Multiple Stores in One Database Source: https://localforage.github.io/localForage Configure multiple instances to point to the same database name while using different store names for data organization. ```javascript const dbName = 'databaseName'; // Create table 1 in databaseName var tableOne = localforage.createInstance({ name : dbName, storeName : 'tableOne', description : '...' }); // Create table 2 in databaseName var tableTwo = localforage.createInstance({ name : dbName, storeName : 'tableTwo', description : '...' }); ``` -------------------------------- ### localforage.createInstance(options) Source: https://localforage.github.io/localForage Creates a new instance of localForage. Each instance maintains its own database and configuration, allowing for isolated data storage. ```APIDOC ## localforage.createInstance(options) ### Description Creates a new instance of localForage and returns it. Each object contains its own database and does not affect other instances. ### Parameters - **options** (object) - Required - Configuration object supporting standard localForage config options, including `name` and `storeName`. ``` -------------------------------- ### Check driver support Source: https://localforage.github.io/localForage Verify if a specific storage driver is supported by the current browser environment. ```javascript localforage.supports(localforage.INDEXEDDB); // true ``` -------------------------------- ### supports Source: https://localforage.github.io/localForage Checks if a specific storage driver is supported by the current browser. ```APIDOC ## supports(driverName) ### Description Returns a boolean indicating whether the specified driver is supported by the browser. ### Parameters - **driverName** (String) - Required - The name of the driver to check. ``` -------------------------------- ### config(options) Source: https://localforage.github.io/localForage Sets and persists localForage configuration options. Must be called before any other localForage calls. ```APIDOC ## config(options) ### Description Set and persist localForage options. This method is synchronous. ### Parameters - **options** (object) - Required - Configuration object containing: - **driver** (string|array) - Preferred driver(s). - **name** (string) - Database name. - **size** (number) - Database size in bytes (WebSQL only). - **storeName** (string) - Name of the datastore. - **version** (number) - Schema version. - **description** (string) - Database description. ### Example ```javascript localforage.config({ name: 'MyDatabase', storeName: 'keyvaluepairs' }); ``` ``` -------------------------------- ### Configure localForage settings Source: https://localforage.github.io/localForage Sets global configuration options like database name, driver preference, and store name. This method is synchronous and must be called before other localForage operations. ```javascript // This will rename the database from "localforage" // to "Hipster PDA App". localforage.config({ name: 'Hipster PDA App' }); // This will force localStorage as the storage // driver even if another is available. You can // use this instead of `setDriver()`. localforage.config({ driver: localforage.LOCALSTORAGE, name: 'I-heart-localStorage' }); // This will use a different driver order. localforage.config({ driver: [localforage.WEBSQL, localforage.INDEXEDDB, localforage.LOCALSTORAGE], name: 'WebSQL-Rox' }); ``` -------------------------------- ### Retrieve data with getItem Source: https://localforage.github.io/localForage Demonstrates retrieving values using Promises, callbacks, or async/await syntax. Note that undefined values are returned as null due to localStorage limitations. ```javascript 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`: 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); } ``` -------------------------------- ### Storing data with localForage Source: https://localforage.github.io/localForage Demonstrates setting values using both Promise-based and callback-based APIs compared to synchronous localStorage. ```javascript // Set a value with localStorage: localStorage.setItem('key', JSON.stringify('value')); doSomethingElse(); // The same code with localForage: localforage.setItem('key', 'value').then(doSomethingElse); // localForage also support callbacks: localforage.setItem('key', 'value', doSomethingElse); ``` -------------------------------- ### localforage.dropInstance(options) Source: https://localforage.github.io/localForage Drops a database or a specific store within a database. Behavior depends on the arguments provided. ```APIDOC ## localforage.dropInstance(options) ### Description Drops the store of the current instance if called with no arguments. If an object with `name` and `storeName` is provided, it drops the specified store. If only `name` is provided, it drops the entire database. ### Parameters - **options** (object) - Optional - An object containing `name` (string) and/or `storeName` (string). ``` -------------------------------- ### driver Source: https://localforage.github.io/localForage Returns the name of the currently active storage driver. ```APIDOC ## driver() ### Description Returns the name of the driver currently in use. Returns null if the driver is still initializing or if initialization failed. ``` -------------------------------- ### clear Source: https://localforage.github.io/localForage Removes every key from the database, returning it to a blank slate. ```APIDOC ## clear(successCallback) ### Description Removes every key from the database, returning it to a blank slate. Use this method with caution as it will remove every item in the offline store. ### Usage ```javascript localforage.clear().then(function() { console.log('Database is now empty.'); }).catch(function(err) { console.log(err); }); ``` ``` -------------------------------- ### getItem(key, successCallback) Source: https://localforage.github.io/localForage Retrieves an item from the storage library. If the key does not exist, it returns null. ```APIDOC ## getItem(key, successCallback) ### Description Gets an item from the storage library and supplies the result to a callback. If the key does not exist, `getItem()` will return `null`. ### Parameters - **key** (String) - Required - The key of the item to retrieve. - **successCallback** (Function) - Optional - A callback function that receives (err, value). ``` -------------------------------- ### Create Multiple localForage Instances Source: https://localforage.github.io/localForage Instantiate separate localForage objects to maintain independent databases that do not share keys. ```javascript var store = localforage.createInstance({ name: "nameHere" }); var otherStore = localforage.createInstance({ name: "otherName" }); // Setting the key on one of these doesn't affect the other. store.setItem("key", "value"); otherStore.setItem("key", "value2"); ``` -------------------------------- ### Iterate over datastore entries Source: https://localforage.github.io/localForage Iterates through all key/value pairs in the database. Returning a non-undefined value from the callback terminates the iteration early. ```javascript // The same code, but using ES6 Promises. localforage.iterate(function(value, key, iterationNumber) { // Resulting key/value pair -- this callback // will be executed for every item in the // database. console.log([key, value]); }).then(function() { console.log('Iteration has completed'); }).catch(function(err) { // This code runs if there were any errors console.log(err); }); // Exit the 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) { // This code runs if there were any errors console.log(err); }); ``` -------------------------------- ### Define a custom driver Source: https://localforage.github.io/localForage Implement a custom driver object with required storage methods and register it using defineDriver. ```javascript // Implement the driver here. var myCustomDriver = { _driver: 'customDriverUniqueName', _initStorage: function(options) { // Custom implementation here... }, clear: function(callback) { // Custom implementation here... }, getItem: function(key, callback) { // Custom implementation here... }, iterate: function(iteratorCallback, successCallback) { // Custom implementation here... }, key: function(n, callback) { // Custom implementation here... }, keys: function(callback) { // Custom implementation here... }, length: function(callback) { // Custom implementation here... }, removeItem: function(key, callback) { // Custom implementation here... }, setItem: function(key, value, callback) { // Custom implementation here... } } // Add the driver to localForage. localforage.defineDriver(myCustomDriver); ``` -------------------------------- ### Store data with setItem Source: https://localforage.github.io/localForage Demonstrates saving various data types, including arrays and binary data from AJAX requests, to the offline store. ```javascript 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 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); }); } }); ``` -------------------------------- ### Drop localForage Instances and Stores Source: https://localforage.github.io/localForage Remove specific stores or entire databases by providing configuration objects to the dropInstance method. ```javascript localforage.dropInstance().then(function() { console.log('Dropped the store of the current instance'); }); localforage.dropInstance({ name: "otherName", storeName: "otherStore" }).then(function() { console.log('Dropped otherStore.') }); localforage.dropInstance({ name: "otherName" }).then(function() { console.log('Dropped otherName database.') }); ``` -------------------------------- ### iterate(iteratorCallback) Source: https://localforage.github.io/localForage Iterates over all value/key pairs in the datastore. The iteratorCallback is executed for every item, and returning a non-undefined value allows for early exit. ```APIDOC ## iterate(iteratorCallback) ### Description Iterate over all value/key pairs in the datastore. The iteratorCallback is called once for each pair with arguments: value, key, and iterationNumber (one-based). ### Parameters - **iteratorCallback** (function) - Required - A function called for each item. Returning a non-undefined value stops iteration early. ### Example ```javascript localforage.iterate(function(value, key, iterationNumber) { console.log([key, value]); }); ``` ``` -------------------------------- ### setDriver(driverName) Source: https://localforage.github.io/localForage Forces the usage of a specific storage driver or a list of drivers in order of preference. ```APIDOC ## setDriver(driverName) ### Description Force usage of a particular driver or list of drivers, if available. Should be called before any data API calls. ### Parameters - **driverName** (string|array) - Required - The driver name (e.g., localforage.INDEXEDDB) or an array of drivers in order of preference. ### Example ```javascript localforage.setDriver(localforage.LOCALSTORAGE); ``` ``` -------------------------------- ### defineDriver Source: https://localforage.github.io/localForage Registers a custom storage driver with localForage. The driver object must implement the required storage methods. ```APIDOC ## defineDriver(driverObject) ### Description Registers a custom driver to be used by localForage. The driver object should implement methods like getItem, setItem, removeItem, and clear. ### Parameters - **driverObject** (Object) - Required - An object containing the driver implementation and a unique _driver name. ``` -------------------------------- ### Set storage driver Source: https://localforage.github.io/localForage Forces the use of a specific storage driver or a prioritized list of drivers. Should be called before any data API calls. ```javascript // Force localStorage to be the backend driver. localforage.setDriver(localforage.LOCALSTORAGE); // Supply a list of drivers, in order of preference. localforage.setDriver([localforage.WEBSQL, localforage.INDEXEDDB]); ``` -------------------------------- ### setItem(key, value, successCallback) Source: https://localforage.github.io/localForage Saves data to an offline store, supporting various JavaScript types including Arrays, Blobs, and Objects. ```APIDOC ## setItem(key, value, successCallback) ### Description Saves data to an offline store. You can store various types of JavaScript objects including Array, ArrayBuffer, Blob, TypedArrays, Number, Object, and String. ### Parameters - **key** (String) - Required - The key to associate with the value. - **value** (Any) - Required - The data to store. - **successCallback** (Function) - Optional - A callback function that receives (err, value). ``` -------------------------------- ### Clear the localForage database Source: https://localforage.github.io/localForage Removes every key from the database. Use with caution as it deletes all items in the offline store. ```javascript localforage.clear().then(function() { // Run this code once the database has been entirely deleted. console.log('Database is now empty.'); }).catch(function(err) { // This code runs if there were any errors console.log(err); }); ``` -------------------------------- ### removeItem Source: https://localforage.github.io/localForage Removes the value of a specific key from the offline store. ```APIDOC ## removeItem(key, successCallback) ### Description Removes the value of a key from the offline store. ### Usage ```javascript localforage.removeItem('somekey').then(function() { console.log('Key is cleared!'); }).catch(function(err) { console.log(err); }); ``` ``` -------------------------------- ### Remove an item from localForage Source: https://localforage.github.io/localForage Removes the value associated with a specific key from the offline store. ```javascript 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); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.