I'm developing a project in Webpack, using vsCode, and I am storing objects in an array, and setting that array in localStorage. This array is called taskList. If a user creates a new task, I create a new object, call it newAddition, get the taskList array from localStorage, push newAddition to it, then set the taskList array back in localStorage. This only runs on a form submit(click event) and is stored in a seperate module ((I'm almost certain this isn't the problem):
const taskList = JSON.parse(window.localStorage.getItem("taskList"));
taskList.push(newAddition);
window.localStorage.setItem("taskList", JSON.stringify(taskList));
Whilst the site is open everything is fine - i can add, delete etc. However, once i close down vsCode, when i restart, my array disappears from localStorage.
In my index.js file(webpack), I have the following code to either pull taskList back out of localStorage, or if it doesn't exist(your first visit), to create a blank array, but every time i restart vsCode, my array is gone. If i keep vsCode open, i can close/restart Firefox and my localStorage is intact. Can someone point out what I'm doing wrong?
const taskList = JSON.parse(window.localStorage.getItem("taskList"));
if (taskList === null) {
const taskListcreate = [];
localStorage.setItem("taskList", JSON.stringify(taskListcreate));
}
Is there something in the default Webpack setup (or webpack.config.js or package.json) that would clear local storage on each restart of the application? I haven't knowingly added anything that would, but that's the only explanation i can currently think of.
The problem was that the live-server extension in vsCode has a setting that uses a random port everytime it gets launched. So if this setting is enabled on your machine, you're going to get a fresh localStorage session on each run.
To fix , open settings.json in the live server extension and check for
"liveServer.settings.port": 0,
Replace the 0 with 5500 like so:
"liveServer.settings.port": 5500,
The 0 tells live-server to use a different port everytime it launches which explains the absence of any values in localStorage, because each time vsCode is accessing localStorage from a different port. By using 5500 specifically, you make sure that it uses port 5500 everytime.