How to store objects in HTML5 localStorage/sessionStorage?

 

HTML5 provides two mechanisms for storing data on the client side: localStorage and sessionStorage. Both of these mechanisms allow you to store data as key-value pairs in the web browser. The key difference between them is in their persistence:

  • localStorage: Data stored in localStorage persists across browser sessions and even after the browser is closed and reopened. It has no expiration time.

  • sessionStorage: Data stored in sessionStorage is only available for the duration of a single page session. It is cleared when the page is closed or refreshed.

Here's how you can store and retrieve objects using localStorage and sessionStorage with examples:

Storing and Retrieving Objects in localStorage:

javascript
// Storing an object in localStorage const user = { name: 'John', age: 30 }; localStorage.setItem('user', JSON.stringify(user)); // Retrieving the object from localStorage const storedUser = JSON.parse(localStorage.getItem('user')); console.log(storedUser); // { name: 'John', age: 30 }

In this example, we store a JavaScript object as a JSON string in localStorage. To store an object, you need to serialize it using JSON.stringify() before storing it, and when you retrieve it, you should parse it using JSON.parse().

Storing and Retrieving Objects in sessionStorage:

javascript
// Storing an object in sessionStorage const product = { id: 1, name: 'Product A', price: 19.99 }; sessionStorage.setItem('product', JSON.stringify(product)); // Retrieving the object from sessionStorage const storedProduct = JSON.parse(sessionStorage.getItem('product')); console.log(storedProduct); // { id: 1, name: 'Product A', price: 19.99 }

The process for storing and retrieving objects in sessionStorage is the same as for localStorage. However, keep in mind that data stored in sessionStorage is only available for the duration of a single page session.

Remember that both localStorage and sessionStorage can only store strings, so you need to serialize and deserialize objects using JSON.stringify() and JSON.parse() as demonstrated in the examples above.

Comments