Details of how to use localStorage in JavaScript

  • 2021-10-27 06:10:14
  • OfStack

If you are a developer and want to enter the world of. NET, you need to know what the possibilities are. Because. NET Framework is the most popular technology in the. NET ecosystem, you can use it to build a variety of applications, but recently, there have been a few new things, such as. NET Core and. NET Standard library. Can we use it in a project or build?

localStorage object is one of the most widely used objects in web programming. It provides a simple solution to store key-value pairs locally on the user's computer.

Most web developers like localStorage API because of its simple syntax and the ability to store up to 5MB of data.

In addition, the latest versions of all major browsers support Web Storage API, including localStorage and sessionStorage. Only Opera Mini does not support webstorage API.

You can quickly verify that your browser supports webstorage API by opening Chrome DevTools. Navigate to Console, type the following code snippet, and press enter.

typeof(Storage)

If you receive 1 undefined, your browser does not support webstorage API. If your browser supports it, you should see "function".

This paper discusses the following issues:

What is localStorage? What is the difference between localStorage and sessionStorage? How to Perform CRUD Operations Using localStorage API What are the pits in common local storage? What are the limitations of localStorage?

What is localStorage?

As mentioned earlier, the localStorage object is part 1 of the webstorage API supported locally by the browser. This is a simple and effective key/value storage solution.

For web developers, the biggest benefit of using localStorage objects is that they can be stored offline. Most importantly, when users close their browsers or restart their computers, we will not lose data. Even after the computer is restarted, the Web site can still use localStorage API to read data stored locally on the user's computer.

This solution provides several interesting use cases for web developers.

Store user settings for a Web site offline Retain user search history Keep the items in the shopping cart

Next, let's compare localStorage with sessionStorage.

What is the difference between localStorage and sessionStorage?

Although the two api look the same, there are subtle differences in how they are executed.

localStorage API is used to store data locally. Therefore, locally saved data is not lost when the user refreshes the tab, closes the browser, or restarts the computer. It is an ideal solution for storing basic data for a long time.

sessionStorage API is still valid after the page is refreshed, but it can only work in the same tab.

In short, be careful when choosing a storage solution for your application. For example, it is best to store user settings information in localStorage. In contrast, sessionStorage is best suited to store data for a specific session.

How to perform CRUD operations using localStorage API

This section shows you how to use localStorage API to add, read, update, or delete. On this basis, I will show you a skill to clear a specific page localStorage.

First, let's create a new key-value pair in the localStorage object. The setItem function accepts 1 key and its value. Choose a suitable name for the key, which you may use to retrieve again.


localStorage.setItem( ' my-key',  ' some-value')

Now let's retrieve the newly created object again.


let item = localStorage.getItem( ' my-key')

console.log(item) // Output:  " some-value " 

It's very simple. Let's continue to update the values of my-key. Note that we use the same setItem function to override its value.


localStorage.setItem( ' my-key',  ' new-value')

Finally, let's delete this key. The removeItem function takes one argument, which is the key you want to delete.


localStorage.removeItem( ' my-key')

To ensure that we have deleted all the keys, let's use the clear function to clear all the contents of the application stored in localStorage.


localStorage.clear()

Now, we are ready for the more advanced localStorage operation.

Advanced localStorage operations: traversal

Let's look at the method for traversing localStorage objects and lookup keys.

The first method uses the most direct for loop. Note that we can use the length property directly on the localStorage object.


for(let i=0; i<localStorage.length; i++) {
 let key = localStorage.key(i)
 console.log(`${key} with value ${localStorage.getItem(key)}`)
}

We can also use the key method directly to retrieve the corresponding key.


for (let i = 0; i < localStorage.length; i++){
 let key = localStorage.key(i)
 console.log(key)
}

Next, let's look at the pits to avoid when using localStorage API.

Common pits in localStorage

Let's look at the two most common pits when interacting with localStorage API.

First, try to store an JSON object. localStorage API is designed to store key-value pairs. Therefore, the value only accepts strings, not objects. However, this does not mean that we cannot store objects. We need to serialize it to a string.


const dinner = { apples: 5, oranges: 1 }
localStorage.setItem( ' my-dinner', JSON.stringify(dinner))

When reading the serialized object, we need to resolve it to JSON again.


let dinner = JSON.parse(localStorage.getItem( ' my-dinner'))

Second, try to store a Boolean value. Similarly, localStorage API only supports strings. Be careful when storing Boolean values.

Fortunately, this solution is similar to storing one JSON object. When a Boolean value is stored, the setItem function converts it to a string like this-"true". To read a Boolean value with a string, we can use the JSON. parse method to convert it back to a Boolean value.


let myBool = JSON.parse(localStorage.getItem( ' my-bool'))

Limitations of localStorage

Here is a quick review of localStorage limitations.

String-based storage Most browsers have limited storage, up to 5 MB Attempts to store huge strings block the main thread. Be sure not to update the same keys at the same time, because this will cause problems. In this case, it is best to look for an alternative storage solution because localStorage API is not designed for this purpose. Web worker or web service cannot access localStorage There is no built-in security mechanism. Therefore, we do not recommend storing passwords or authentication-related data. Anyone with access to the user's browser can open a page and read the information stored in localStorage, just like a publicly available computer in a library.

Related articles: