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>