Display all items currently stored in the localStorage on a webpage

My form data is being stored in local storage like this:

Object {title: "dsadasds", dueDate: "dsadasdsa", summary: "dsadadas", body: "dasdasdas"}
Object {title: "dasdadsa", dueDate: "dasdasdadasda", summary: "dsadasdasd", body: "dasdasdas"}

Each time a user submits the form, the data gets saved in local storage. On a separate page 'localhost:3000/notes', I want to display all these objects stored in localStorage. However, my current code only shows the last object submitted.

        var form = $('#form'),
        formTitle = $('#title'),
        formDueDate = $('#dueDate'),
        formSummary = $('#summary'),
        formBody = $('#body');

        var title = formTitle.val();
        var dueDate = formDueDate.val();
        var summary = formSummary.val();
        var body = formBody.val();
        var newContent2 = $('#new-content2')

        var test = {};
        test = {
            title: title,
            dueDate: dueDate,
            summary: summary,
            body: body
        }

        localStorage.setItem('test', JSON.stringify(test));
        var LocalStoredData = JSON.parse(localStorage.getItem('test'));
        console.log(LocalStoredData);

       //for retrieving data from locastorage
       var retrievedData =  localStorage.getItem('test');
       var text = JSON.parse(retrievedData);
       var showTitle = text["title"];
       var showDueDate=  text["dueDate"];
       var showSummary = text["summary"];
       var showBody = text["body"];

       $('#showTitle').html(showTitle);
       $('#showDueDate').html(showDueDate);
       $('#showSummary').html(showSummary);
       $('#showBody').html(showBody); 

I'm attempting to loop through all the objects to extract them from localStorage and display them in appropriate div on the web page. I tried using this loop:

for(var i=0;i<localStorage.length;i++)

However, nothing is showing up with this loop. How can I successfully display all the objects present in my localStorage?

Answer №1

The hunt is on

for (let index=0; index<localStorage.length; index++) {
    let localKey = localStorage.key(index);
    let storedItem = localStorage.getItem(localKey);
    try {
        storedItem = JSON.parse(storedItem);
    } catch(error) {
        console.log(localKey + " is not in JSON format");
    }
    …
}

Answer №2

If you want to retrieve all the data stored in LocalStorage, you can simply use the Object.keys method like this:

Object.keys(localStorage).forEach(item => {
  console.log(item, localStorage.getItem(item))
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some alternative ways to utilize jQuery siblings() without restricting it to the same parent element?

In the code provided below as Non-functional code [1], it will function correctly with siblings() to disable other input fields if their sum or amount exceeds a specified maximum value. This works effectively when all input fields are within the same paren ...

Unfortunately unable to retrieve data with Meteo HTTP call

I've encountered a peculiar issue with meteor. I'm attempting to perform an HTTP call and utilize the retrieved data in a React component, but I'm unable to access the data returned. On the server: 'get': function get() { try ...

What is preventing Protractor from detecting Angular on a site that has been automatically initialized with Angular?

Whenever I try to utilize browser.get() in my code, I encounter the following error: Error: Angular could not be found on the page http://localhost:5000/#/login debug=timing&saveLogs=true&displayAll=true : angular never provided resumeBootstrap A ...

Transmitting information from Angular to Laravel

Hey, I'm facing a challenge once again. Currently, I am working on creating a to-do list application using Laravel and Angular. While I can successfully retrieve data from the database through the Laravel and Angular controllers, I'm encountering ...

What is the best way to transfer a multidimensional array from PHP to JavaScript?

Attempting to extract array value from a JSON string, I utilize the json_decode function in PHP. <?php $jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php'); $jsonDecoded=json_decode($jsonContent,true); foreach($jsonEncoded[&apo ...

update certain parts of a webpage using ajax and still allow users to

Currently, I am implementing a partial update feature on the page using Ajax for a shopping cart. The cart updates in real-time as users add items to it. However, there is an issue when users navigate to the checkout page and then click the back button - t ...

Adjusting Media Queries according to the browser window's zoom level

Is there a way to detect the browser width dynamically? For instance, can I adjust the CSS styling based on zoom adjustments like ctrl + or ctrl -? By "box," I am referring to a perfectly square shape. So, when the browser width is 100%, I want a layout wi ...

Looking to restrict the data retrieved from an API while utilizing ReactJS

I am currently fetching transaction data from an API. One of the fields in the response is buyer, which may sometimes be null. As a result, I am excluding any entries with a null buyer. This leads to varying numbers of results being displayed. My goal is t ...

What is the best approach for parsing JSON data and dynamically populating multiple attributes or inner HTML elements?

Let's consider a scenario where we have a program sending an ajax request to a PHP file, and this program needs to utilize the response values for tasks like: Updating form inputs Setting checkboxes Updating the innerHTML of elements The code below ...

Retrieving the value of an object based on a dynamic key in Typescript

Currently, I am facing an issue with exporting a single value from a configuration object based on the process.env.NODE_ENV variable. Specifically, I am attempting to retrieve the value of the configEnvs variable like this: configEnvs['local']. H ...

Troubleshooting Problem with Accordion Size in CSS

I am facing an issue with a dropdown menu that I have created. The dropdown has parent and child rows to display controls, but the width of the Accordion is not stretching as expected despite being set to 100%. Using Chrome and Edge developer tools, I insp ...

Initiate an Ajax request to interact with a TYPO3 controller method

Is there a way to utilize ajax within the Typo3 Backend in order to call a controller function from my own extension? I am interested in performing searches within my repository. For instance: I would like to have an Input field where I can input a Name ...

Creating a dynamic textarea input based on the number entered using AngularJS

Can a loop be simplified in AngularJs to easily determine the number of textarea inputs a user can fill? <input type="number" class="form-control" min="1" max="4" value="1"> <div ng-repeat="..."> <div class="form-group"> < ...

Steps to resolve the issue: ERROR Avoid nesting VirtualizedLists inside regular ScrollViews. This error can occur even if you are not using ScrollViews

I'm currently working on a react-native app and I need to create a layout with components arranged vertically, including a transaction history section. However, I'm encountering an issue when trying to display the transaction history data from du ...

I love the idea of the music playing on as I navigate between pages or tabs. Such a cool feature with Next

I'm looking to implement a music player within my next.js application. How can I ensure that the currently playing track doesn't stop when switching between pages? Essentially, I want the music playback to continue seamlessly as users navigate th ...

Issue: Assertion violation: The use of <Link> element is restricted to within a <Router>. Any solutions or suggestions?

In my React and Next Js application, I am utilizing react-router-dom for routing purposes. The dependencies listed in the package.json file are as follows: This is how my current package.json file looks: { "name": "MUSIC", "versio ...

issue encountered when attempting to respond to ajax request with file

Have been working with jquery jtable to send ajax request in order to retrieve an excel file from the server. However, I am facing an issue where Response::download function is not functioning as expected. $writer = (new WriterFactory())->createWri ...

Creating an arc within a polyline in THREE.JS

My data consists of the following points: "POLYLINE":[[ {"x":"-6094.1665707632401","y":"3074.764386330728","r":""}, {"x":"-699.22595358468595","y":"1099.941236568309","r":""}, {"x":"-4940.397089330264","y":"576. ...

Encounter an Internal Server Error while using Laravel 5.4

I am encountering an issue while attempting to implement ajax search in my laravel project. I have included the controller and JavaScript code related to this problem below. Can you please take a look and let me know what may be causing the error? pu ...

In the Redux framework, the reducer fails to identify the action object

I'm currently working on a React project using Redux. I've encountered an issue where my reducer is not recognizing the action type being sent to it, or even the action itself. The error message I am receiving is TypeError: Cannot read property & ...