The open blogging platform. Say no to algorithms and paywalls.

How To Store JSON Data In Local Storage - JS, React, Angular

Learn how to store data in localStorage in JavaScript, React, or Angular.

image

You can store some data ( about 5MB but check here) in the browser by using the localStorage or sessionStorage object.

Angular, React, and JSON logo

Angular, React, and JSON logo

Using the localStorage object, the data stored in the browser has no expiration time.

However, you should remember that browsing using an "incognito" session will clear data when the last "private" tab is closed.

This post won't cover the differences between localStorage and sessionStorage, but it's good to know them.

Store Data In LocalStorage --- JavaScript

Store JSON Data In localStorage using plain JavaScript

Store JSON Data In localStorage using plain JavaScript

Here is what you need to know.

You can save data in localStorage by using the following syntax

localStorage.setItem(variableKey, variableValue);

This is fine when variableValue is a simple string, but it won't work for more complex structures like objects. When you have objects, or JSON data, you will need to use the JSON.stringify() method.

Store JSON Data

Here is an example where we store an object into storage.

// Create an object
const userData = {
  job: "Programmer",
  skills: [
    { id: 4200, name: "Angular" },
    { id: 3000, name: "React" },
    { id: 8080, name: "Vue" },
  ],
};

// Store the object into storage
localStorage.setItem("userData", JSON.stringify(userData));

Read JSON Data

How do you know if it works? By trying to read the data you just saved.

// Retrieve the object from the storage
const data = localStorage.getItem("userData");
console.log("data: ", JSON.parse(data));

Note that using the JSON.parse() method is not always necessary! If you just want to check what's inside the storage, you can simply log data.

Delete JSON Data

Finally, you may want to delete data from*localStorage*.

There are two ways: removeItem() and clear().

By using removeItem() you only delete values associated with the key you pass in, e.g. 'userData' in the example below.

localStorage.removeItem('userData');

By using clear() you will delete everything in the localStorage area associated with the app you are using.

localStorage.clear();

It would be more precise to say that it deletes data in the localStorage area associated with a URL. Read further to understand more.

Good To Know

As reported on MDN, *localStorage* data is specific to the protocol of the document.

What does it mean?

It means that for every URL the browser is likely to create a new "bucket" where it stores data.

Say that you are working with HTML and JS on your laptop. When you open the HTML file in the browser, the URL will look similar to this:

file:///C:/Users/John/webProjects/appName/localStorage.html

According to MDN, In all current browsers, *localStorage* seems to return a different object for each *file:* URL. In other words, each *file:* URL seems to have its own unique local-storage area. But there are no guarantees about that behavior, so you shouldn't rely on it.

In my case, despite changing parts of the URL, localStorage seems to return the same object.

Store Data In LocalStorage --- React

Store JSON Data In localStorage using React

Store JSON Data In localStorage using React

What's different in React?

Not much! We can use the same JavaScript code to store and retrieve data from localStorage. Remember useEffect!

One step at a time.

Once you have an object, you can store it and retrieve it as follow:

function App() {
localStorage.setItem("userData", JSON.stringify(userData));

const data = localStorage.getItem("userData");
 console.log("data: ", JSON.parse(data));

return (
    // ...
)
}

However, there is something to remember! If we look at the console, we'll see that React logged twice! At least it is the same object!

In the console, we can see that React logs the same object twice

React logs data twice

Why Is React Logging Twice?

React logs the same object twice because of the component lifecycle method.

React Component Lifecycle Method: Mounting, Updating, and Unmounting.

React Component Lifecycle Method

Since both Mounting and Updating trigger a render, the code inside your component is executed twice.

In my case, the console.log is in App() therefore it gets executed when the component mounts and when it updates.

When you work with side effects in React, you may want to use useEffect.

The code becomes:

function App() {
localStorage.setItem("userData", JSON.stringify(userData));

useEffect(() => {
 const data = localStorage.getItem("userData");
 console.log("data: ", JSON.parse(data));
 }, []);

return (
    // ...
    )
}

Be aware that you need to import useEffect.

Furthermore, remember that if you have React.StrictMode wrapping around your App component, React will render twice.

As reported on StackOverflow, *StrictMode*renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).

Go to index.js and remove React.StrictMode if necessary.

// index.js

// ...

root.render(

{" "}

<React.StrictMode>
    // remove this!
  <App />
</React.StrictMode> // and this!
);

Store Data In LocalStorage --- Angular

Store JSON Data In localStorage using Angular

Store JSON Data In localStorage using Angular

What's different in Angular?

Not much! We can use the same JavaScript code to store and retrieve data from localStorage.

In the following example, I am adding the code to AppComponent.

Everything happens inside ngOnInit.

export class AppComponent implements OnInit {
  userData = {
    // ...
  };

  ngOnInit() {
    localStorage.setItem("userData", JSON.stringify(this.userData));
    const data = localStorage.getItem("userData");
    console.log("data: ", JSON.parse(data));
  }
}

As a side remark, it could be more appropriate to work with effects from a service.

Summary

  • Store data: localStorage.setItem(key, value)
  • Read data: localStorage.getItem(key)
  • To store JSON data, convert the value with JSON.stringify(value)
  • To convert JSON data JSON.parse(value)
  • In React, use useEffect to deal with side effects. You might need to remove React.StrictMode
  • In Angular, just use plain JavaScript inside ngOnInit, or where you prefer!



Continue Learning