localforage persistent storage solution

localForage description:
localForage is a JavaScript library for offline storage in web browsers. It provides a simple API that allows developers to store and retrieve data using an asynchronous key/value store. The main goal of localForage is to provide a cross-browser, persistent storage solution so that data is preserved regardless of which browser or device the user uses to access it. It uses various backend storage technologies such as IndexedDB, Web SQL, and localStorage (when available) to provide the best compatibility and performance. Using localForage, developers can store data on the user’s device and access it without a network connection. This is useful for building offline applications or optimizing the experience of online applications. localForage also provides some convenient methods, such as automatically serializing and deserializing data, and setting expiration time. In summary, localForage is a powerful yet simple tool that can help developers implement offline storage capabilities in web browsers and improve application reliability and performance.

You can refer to the official documentation of localForage for more details and usage: localForage

To use localForage in a Vue project, you first need to install the localForage library. You can install it through npm or yarn, run the following command:

npm install localforage

After the installation is complete, introduce the localForage library into the Vue component and use its API for data storage and retrieval. Here’s a simple example:

<template>
  <div>
    <button @click="saveData">Save data</button>
    <button @click="getData">Get data</button>
  </div>
</template>

<script>
import localforage from 'localforage';

export default {
  methods: {
    saveData() {
      localforage.setItem('myKey', 'Hello, localForage!')
        .then(() => {
          console.log('Data saved successfully');
        })
        .catch((error) => {
          console.error('Data saving failed:', error);
        });
    },
    getData() {
      localforage.getItem('myKey')
        .then((value) => {
          console.log('Data obtained:', value);
        })
        .catch((error) => {
          console.error('Failed to obtain data:', error);
        });
    }
  }
}
</script>

In the above example, we introduced the localforage library in the Vue component. In the method saveData, use the localforage.setItem method to save the data to local storage. In the method getData, use the localforage.getItem method to get data from local storage.

localForage also provides many other useful APIs, such as deleting data, clearing storage, etc.: To delete data stored in localForage, you can use the removeItem method or clear method.

Use the removeItem method to delete the data of the specified key

import localforage from 'localforage';

//Delete the data of the specified key
localforage.removeItem('myKey')
  .then(() => {
    console.log('Data deleted successfully');
  })
  .catch((error) => {
    console.error('Data deletion failed:', error);
  });

In the above code, we use the removeItem method to delete the data with the key ‘myKey’. In the then callback of Promise, the message “data deletion successful” can be printed. If the deletion operation fails, an error message will be output in the catch callback.

Use the clear method to clear all data

import localforage from 'localforage';

// Clear all data
localforage.clear()
  .then(() => {
    console.log('Data cleared successfully');
  })
  .catch((error) => {
    console.error('Data clearing failed:', error);
  });

In the above code, we use the clear method to clear all data in localForage. Similar to the removeItem method, success or failure can be handled in Promise’s then callback or catch callback.

VUE recommends using Pinia to manage localForage

Install Pinia and localforage:

npm install pinia localforage

Set up the Pinia instance and localforage in the entry file of the Vue application:

// main.js
import Vue from 'vue';
import { createPinia } from 'pinia';
import localforage from 'localforage';
import { createPlugin } from 'vue-pinia';

const pinia = createPinia();
Vue.use(createPlugin(pinia));

localforage.config({
  //Configuration items
});

newVue({
  pinia,
  //Other configuration items
}).$mount('#app');

In the above code, we first imported the createPinia function, localforage and createPlugin function. Then, use createPinia to create a global Pinia instance and register it as an option of the Vue instance. Next, we use the localforage.config method to configure localForage. Finally, the Pinia plug-in is installed through Vue.use.

Create and register Pinia store for managing localForage

If you want to use multiple databases, it is recommended to manage all databases uniformly through pinia, so that the flow of data will be clearer, and database-related operations will be written in the store, making your database more standardized.

// store/indexedDB.ts
import { defineStore } from 'pinia'
import localforage from 'localforage'

export const useIndexedDBStore = defineStore('indexedDB', {
  state: () => ({
    filesDB: localforage.createInstance({
      name: 'filesDB',
    }),
    usersDB: localforage.createInstance({
      name: 'usersDB',
    }),
    responseDB: localforage.createInstance({
      name: 'responseDB',
    }),
  }),
  actions: {
    async setfilesDB(key: string, value: any) {
      this.filesDB.setItem(key, value)
    },
  }
})

When we use it, we directly call the method in the store

import { useIndexedDBStore } from '@/store/indexedDB'
const indexedDBStore = useIndexedDBStore()
const file1 = {a: 'hello'}
indexedDBStore.setfilesDB('file1', file1)

localForage and localStorage are two mechanisms for client-side storage of data. They have some differences and their own advantages and disadvantages.

  1. the difference:

    • API and functions: localStorage is part of the Web Storage API, providing simple key-value pair storage and can only store string type data. LocalForage is encapsulated based on technologies such as IndexedDB, WebSQL and localStorage, providing more powerful APIs and functions, and can store complex data types (such as objects, arrays, etc.).
    • Capacity: The capacity of localStorage is usually about 5MB, while the capacity of localForage depends on the underlying technology used (such as IndexedDB), which can generally reach 10MB or more.
    • Asynchronous support: localForage supports asynchronous operations, which can better handle reading and writing large amounts of data; localStorage is synchronous and may block the main thread.
    • Data storage location: localStorage data is stored locally in the browser, while localForage can choose to store data in IndexedDB, WebSQL or localStorage, giving it greater flexibility.
  2. advantage:

    • Compared with localStorage, localForage has more powerful functions and APIs and can handle complex data types more flexibly.
    • localForage supports asynchronous operations and is more efficient for reading and writing large amounts of data.
    • The capacity of localForage is generally large and suitable for storing larger amounts of data.
  3. shortcoming:

    • localForage is more complex than localStorage and requires the introduction of additional libraries and dependencies.
    • localForage uses technologies such as IndexedDB and WebSQL as underlying storage, and may not fully support some lower version browsers.
    • localForage may perform slightly worse in some specific scenarios, such as frequent small data writes.

To sum up, if you need simple key-value pair storage and a small amount of data, you can choose to use localStorage. If you need to handle complex data types, have a large amount of data reading and writing requirements, or want to provide better scalability and asynchronous support, then localForage will be more suitable.