How do I prevent the local storage from being deleted after reload and insert a new entry from my input fields? I want to display the data that I saved in a list in HTML.
// when I add new items in my form and submit it, the old entries in local-storage gets deleted
let datas = [];
const addEntry = e => {
e.preventDefault();
let data = {
id: document.querySelector("#date").value,
situation: document.querySelector("#situation").value,
mood: document.querySelector("#mood").value,
special: document.querySelector("#special").value,
expectations: document.querySelector("#expectations").value,
fulfilled: document.querySelector("#fulfilled").value,
};
datas.push(data);
console.log(datas);
document.querySelector("form").reset();
localStorage.setItem("smokeEntries", JSON.stringify(datas));
};
let content;
//get object and save in array variable
const getEntriesFromLocalStorage = () => {
content = [JSON.parse(this.localStorage.getItem("smokeEntries"))];
};
document.addEventListener("DOMContentLoaded", () => {
document.querySelector("#submit").addEventListener("click", addEntry);
});
Personally I wouldn't try to keep two arrays (datas and content) in sync as it can cause inconsistency problems like this where you're using one to update and store information in state management and the other displayed visually are out of sync. I'd suggest combining them like this:
let content = [];
const addEntry = e => {
e.preventDefault();
let data = {
id: document.querySelector("#date").value,
situation: document.querySelector("#situation").value,
mood: document.querySelector("#mood").value,
special: document.querySelector("#special").value,
expectations: document.querySelector("#expectations").value,
fulfilled: document.querySelector("#fulfilled").value,
};
content.push(data);
document.querySelector("form").reset();
localStorage.setItem("smokeEntries", JSON.stringify(content));
};
const getEntriesFromLocalStorage = () => {
content = [JSON.parse(localStorage.getItem("smokeEntries"))];
};
document.addEventListener("DOMContentLoaded", () => {
document.querySelector("#submit").addEventListener("click", addEntry);
});
There also may be some problem with setting content (because we're wrapping it in brackets ([]) but it may already be an array -- should be pretty obvious after you run it, remove the brackets if it turns into nested arrays) but I haven't ran the code. Also note that for content to load "state" you'll need to call getEntriesFromLocalStorage() before using the state (or possibly trigger a re-render after).