I am running an application via VSCode's Live Server extension.
This application (e-commerce website) saves items to a cartItems array that gets written to localStorage whenever an addToCart button is clicked. I can see in DevTools/Application/LocalStorage that the items are being saved correctly when the specified actions are taken.
However, my localStorage is cleared whenever I refresh the page or navigate to a different page within the same application.
When writing items to localStorage, I have tried invoking the localStorage short-hand, as well as the more explicit window.localStorage. Neither has worked for this issue.
Does localStorage not persist when an application is run locally or via a live server? I suspect it should and I am doing something else incorrectly.
The MDN documentation mentions:
The read-only
localStorageproperty allows you to access aStorageobject for theDocument's origin; the stored data is saved across browser sessions.localStorageis similar tosessionStorage, except that while data stored inlocalStoragehas no expiration time, data stored insessionStoragegets cleared when the page session ends — that is, when the page is closed. (Data in alocalStorageobject created in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.)
Could it be that each refresh or page change on live server represents an entirely new device history? (Again, this feels plausible but still unlikely. I am happy to be wrong, however.)
Thank you in advance for any guidance you can provide.
EDIT - Here is some of the relevant code:
In the global scope:
const cartItems = [];
localStorage.setItem('cartItemsKey', JSON.stringify(cartItems));
localStorage.getItem('cartItemsKey');
const cartItemsInStorage = localStorage.getItem('cartItemsKey');
Encapsulated - this function fires when an addToCart button is clicked. Omitting most of it, except the part pertaining to localStorage, for brevity:
function addToCart (button) {
// Create newCartItem object using relevant data
cartItems.push(newCartItem);
localStorage.removeItem('cartItemsKey');
localStorage.setItem('cartItemsKey', JSON.stringify(cartItems));
}
Again, I can see that the items are successfully being saved to localStorage, per the below screen recording. It's when I refresh or change pages that I have trouble.
