How to Store and Retrieve Arrays in localStorage

Jasser Mark Arioste

Jasser Mark Arioste

How to Store and Retrieve Arrays in localStorage

In this tutorial, you'll learn how to store and retrieve an array of objects in localStorage.

Introduction to localStorage API #

localStorage is a key-value storage mechanism available in web browsers that allows web developers to store and retrieve data on the client-side. It's part of the Web Storage API, along with sessionStorage, and it provides a simple way to store data that persists even after the browser is closed.

localStorage is used to store data locally in the user's browser and this data can be manipulated by the javascript code running in the user's Browser. This data is scoped to the domain of the website. Data stored in localStorage for one website is not accessible to other websites, which enhances security and privacy.

localStorage is supported in all modern web browsers, making it a reliable choice for client-side data storage in web applications.

Basic usage of localStorage #

There are 3 data-types you can store in localStorage: string, number, and boolean. For these three data-types, there's no extra step necessary to store or retrieve the data. For example, if you want to store data, you can do so by the following code:

// store a value
localStorage.setItem('mykey', 'dinosaur')
localStorage.setItem('mynumber', 2)
localStorage.setItem('isLoggedIn', true)

// retreive a value using the key
localStorage.getItem('mykey') // 'dinosaur'
localStorage.getItem('mynumber') // 2
localStorage.getItem('isLoggedIn') // true

Storing Arrays in localStorage #

Since there are only three data-types you can store in localStorage, we first have to transform the array into a string using JSON.stringify(). For example:

const myArray = ['a','b','c', 'd','e']
// convert array to JSON string 
const myArrayStr = JSON.stringify(myArray)
// store the stringified array to localStorage with 'my-array' as key
localStorage.setItem('my-array', myArrayStr)

Retrieving Arrays in localStorage #

When retrieving the array, first we use localStorage.getItem to get the value as a string format. Then we use JSON.parse() to convert them back to the original format. For example:

// get the stringified value from localStorage
const myArrayStr2 = localStorage.getItem('my-array')

// transform the stringified value using JSON.parse
const myArray2 = JSON.parse(myArrayStr2) // ['a','b','c', 'd','e']

Error Handling #

When working with arrays in localStorage, various errors, and unexpected situations can arise. Let's understand how to handle these errors to create a robust application.

Error 1: Key Doesn't Exist #

Sometimes, when retrieving an array using a specific key, the key may not exist in localStorage, resulting in a null value. First, check if the retrieved value is null, and gracefully handle this situation by providing a fallback value to the user. For example:

// get the stringified value from localStorage
const myArrayStr2 = localStorage.getItem('my-array') ?? "[]" //provide a default empty stringified array
const myArray2 = JSON.parse(myArrayStr2)

Error 2: Quota Exceeded #

localStorage has a storage limit (typically around 5-10 MB per domain), and if you exceed this limit by storing large arrays or too much data, you'll encounter a "Quota Exceeded" error.

Error 3: Data Type Mismatch #

If you don't properly parse the data retrieved from localStorage, you may encounter type mismatches when trying to use arrays or objects. Always use JSON.parse() to convert data retrieved from localStorage back into its original format (e.g., arrays). Verify that the parsed data is of the expected type before using it to avoid type-related errors.

Error 4: Security Errors #

Attempting to access localStorage from an insecure context, such as an HTTP website trying to access localStorage in a secure (HTTPS) iframe, can result in security errors. Ensure that your website or web application uses HTTPS and that all embedded content is loaded securely.

Error 5: Storage Errors #

Sometimes, the browser's localStorage storage may become corrupt or inaccessible, leading to storage-related errors. While you can't directly control browser storage errors, you can implement robust error-handling strategies in your code. For example, use try-catch blocks to catch and log any unexpected errors, and provide feedback to users when errors occur. For example:

export function getArrayItem(key:string) {
  try {
    #tsx| |true
    // get the stringified value from localStorage
    const myArrayStr2 = localStorage.getItem('my-array') ?? "[]" //provide a default empty stringified array
    const myArray2 = JSON.parse(myArrayStr2)
    return myArray2
  } catch(e){
    return []

Conclusion #

You learned how to store and retrieve arrays in localStorage. You also learned different errors associated with retrieving and storing data to localStorage and how to handle them.

Credits: Image by xiSerge from Pixabay

Share this post!

Related Posts


This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle