Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2023 › #HowTo #Javascript

How to display data from localStorage in JavaScript

We can use the getItem() method of the localStorage object to get the saved data from localStorage.

Syntax #

localStorage.getItem(key)

To display data from localStorage, first We need to store data in local storage using the setItem() method. The example is given below.

Example : save data in localStorage. #
<script>
 localStorage.setItem('L1','message 1')
 console.log(localStorage.getItem('L1')) 
</script>

In the above example, we have passed two parameters inside the setItem() method. The first one L1 is the name and the second one message 1 is the value we want to save in localStorage.

Now if we want to access the saved data from localStorage, we can simply use the getItem() method.

console.log(localStorage.getItem('L1'))

L1 is the name, we have used when we saved data in localStorage.

save
listen
AI Answer
1 Answer
Write Your Answer
  1. The first step is retrieving the value from local storage using its key name.
    <script>
    let myData = window.localStorage.getItem('myData');
       console .log (myData ) ;
    </script>

    Once retrieved, you can then parse your string into an object or array depending on what type of structure was used when saving.
    <script>
    let parsedMyData= JSON.parse(myData);
    console.log(parsedMyData);
    </script>

    Output :
      {property1: "value1", property2:"value2"} //if saved as an Object before .
      [item1,"item 2","item3"] //if saved as Array before  

    Now that our value has been parsed successfully, we can loop through each element and create HTML elements accordingly .
    Reply Delete
    Share
loading
back
View All