Upon reloading the page, the local storage is reset

I'm brand new to JavaScript. I have a piece of code here that creates an array of objects based on user inputs and saves it in the localStorage.

I'm looking to ensure that the data saved in localStorage persists even after the page is reloaded.

After some research, I came across a solution which involves using the following line of code:

localStorage.setItem("initData"+new Date().getTime(), JSON.stringify(movies))
But this method doesn't allow me to store all the objects in an array.

    <script>
        
        let movies = [];
        const addMovie = (ev)=>{
            ev.preventDefault();  //to stop the form submitting
            let movie = {
                id: Date.now(),
                title: document.getElementById('title').value,
                sales: document.getElementById('sales').value
            }
            movies.push(movie);
            document.forms[0].reset(); // to clear the form for the next entries
            //document.querySelector('form').reset();

            //for display purposes only
            console.warn('added' , {movies} );
            let pre = document.querySelector('#msg pre');
            pre.textContent = '\n' + JSON.stringify(movies, '\t', 2);

            //saving to localStorage
            localStorage.setItem('initData', JSON.stringify(movies) );


            let allsales = movies.map(({ sales }) => sales)
            var allsalesnumbers = allsales.map(Number);
            var sumSales = allsalesnumbers.reduce(function(pv, cv) { return pv + cv; }, 0);
            console.log("Total of EU Sales " + sumSales );

                       
        }
        document.addEventListener('DOMContentLoaded', ()=>{
            document.getElementById('btn').addEventListener('click', addMovie);
        });
    </script>

Answer №1

Remember, LocalStorage can only store strings. To save an array, you must stringify it before storing and then parse it when reading.

let movieList =  JSON.parse(localStorage.getItem('movieList')) || [];

//save to localStorage:

localStorage.setItem('movieList', JSON.stringify(movieList));

Answer №2

It appears the issue lies in not utilizing the existing stored data, instead consistently replacing it with new data upon submission. To address this, consider initializing the movies array as follows:

const savedDataString = localStorage.getItem('initData')
const movies = JSON.parse(savedDataString || "[]") // Parses an empty array if no items are present

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

Automate Facebook Photo Untagging using JavaScript

After spending hours working on it, I want to create a JavaScript routine that can automatically untag me from photos on Facebook. My plan is to run this in the Firebug console so I can untangle myself from all Facebook photos, as there's no way to do ...

|Webview|Best Practices for Integrating Upload Script

I am currently developing an Android app using WebView and I need to implement a code for uploading on Android. I came across the following code snippet and I want to convert it into JavaScript instead of Java (if possible). It needs to be linked to the up ...

Discovering duplicated arrays within a sequence

I am facing an issue with my Python code. I have a list containing approximately 131,000 arrays, each with a length of 300. My goal is to identify which arrays are repeating within this list by comparing each array with the others. Here is what I have trie ...

Exploring the Use of 7BitEncodedInt in JavaScript

Currently, I am trying to read a binary file using JavaScript. It appears that this file may have been written in C#, which handles strings differently from how it's done in the source mentioned at https://learn.microsoft.com/en-us/dotnet/api/system. ...

I am facing difficulties in installing the necessary node modules for my Angular project

After attempting to run npm install, an error message is displayed towards the end: error syscall unlink 22396 error The operation was rejected by your operating system. 22396 error It's possible that the file was already in use (by a text editor or ...

What advantages does declaring a backing model "class" that closely resembles the GraphQL "Type" bring when using GraphQL?

I appreciate the Universal Relay Boilerplate for its meticulous organization and thoughtful structure compared to other boilerplates. It seems like they really put a lot of effort into ensuring everything is well-planned from the start, which is not always ...

Paginating content without the need for a database

Seeking assistance on implementing pagination for displaying trading history API responses, without utilizing a database. Can anyone provide guidance and help with the necessary logic? Here is an excerpt of my code: <?php error_reporting(E_ALL) ...

Generate a randomly structured 2D array called "Array" using JavaScript

Can anyone help me with extracting a random array from a 2D named array? I've tried several solutions but none of them seem to work. var sites = []; sites['apple'] = [ 'green' , 'red' , 'blue' ]; sites['o ...

Clear the text in a textarea after submitting the form

I am facing an issue with a comment box (textarea) inside a dialog. After successfully saving the comment, I want to clear the content of the textarea and close the dialog box. Currently, the dialog box closes, but the content remains in the textarea. < ...

Avoiding HTML injection in custom directives

In my custom directive, I have implemented the functionality to render strings with LaTeX using MathJax.js. Below is the code snippet: MathJax.Hub.Config({ skipStartupTypeset: true, tex2jax: { inlineMath: [['$','$'], [&ap ...

Harness the power of Angular 2 CLI to create dynamic and interactive

I've exhausted all options available. I'm working with a very straightforward ng2 app. Here is the structure of the files: mean |- client (where the ng2 app is housed) | |- dist | |- (all ng2 app directories)... |- node_modules |- rou ...

Clear Android's sessionStorage and localStorage for all applications

In my current scenario, I have a main application that serves as the launching pad for a group of other webview-based applications. The catch is, my main application isn't classified as a system app and therefore I can't sign it as one. Upon l ...

React Router is not compatible with ReactJS app version 18

After using the command npx create-react-app, I've just set up a new ReactJS app which I think is running on React version 18 (feel free to correct me if I'm mistaken). Now, as I attempt to implement a router for this app, I find myself hesitati ...

What could be causing the video not to display in landscape mode on the iPad Pro?

I'm having an issue with a standard HTML5 <video> on my website. The videos are working fine on most devices, however there is a problem specifically with the iPad Pro in landscape orientation. It seems to work properly in portrait orientation ...

Converting JSON data into a PHP array is not within my capabilities

Can anyone help me figure out why I'm having trouble converting this JSON data into a PHP array? {"sides0":{"name_nl":"Voorkant100","name":"Frontside100","template_overlay":""},&quo ...

When buttons contain an image instead of text, event.target.value will be undefined

I'm facing an issue with two buttons that are almost identical, except one includes an image while the other has text content. I have added onClick event handlers to both of them. Oddly, the event.target.value for the image button is coming up as und ...

Print out the error message: "ERROR [ExceptionsHandler] Unable to access the property 'log' as it is undefined."

Just starting out with Nestjs and JavaScript but ran into an error when trying to print a text line using console.log() const my_text ="123" console.log(my_text) https://i.sstatic.net/xPnzX.png ...

AngularJS validation loses synchronization when eliminating a form element

I have a form that includes multiple input fields, allowing users to remove them as needed. var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.numbers = [1,2,3]; $scope.deleteField = ...

Partial sort using lodash orderby

I have an array containing elements as displayed below. My requirement is to partially sort the array, where all elements with fix===1 should come first in their original order. The remaining elements (fix==0) should then follow sorted by their jobDueDate. ...

Navigational mapping tool with interactive user interface

I'm currently utilizing geomap to visualize the location using the following code snippet: function OnLoad() { $.ajax({ type: "POST", **url: "CS.aspx/CreateWorldMap"**, data: '{}', ...