Search code examples
javascriptvisual-studio-codelocal-storagepersistence

Should localStorage persist when application is run via live server?


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 localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed. (Data in a localStorage object 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.

local-storage-issue


Solution

  • Update:

    I figured out what the issue was.

    I have the following code in the global scope:

    const cartItems = [];
    localStorage.setItem('cartItemsKey', JSON.stringify(cartItems));
    localStorage.getItem('cartItemsKey');
    const cartItemsInStorage = localStorage.getItem('cartItemsKey');
    

    Which gets called before this code:

    function addToCart (button) {
        // Create newCartItem object using relevant data
        cartItems.push(newCartItem);
            localStorage.removeItem('cartItemsKey');
            localStorage.setItem('cartItemsKey', JSON.stringify(cartItems));
    }
    

    So I was effectively re-writing an empty array into localStorage every time the page reloaded.

    I have resolved this issue by removing the .setItem line as follows:

    const cartItems = [];
    localStorage.getItem('cartItemsKey');
    const cartItemsInStorage = localStorage.getItem('cartItemsKey');
    

    Now, I will rewrite my initial const cartItems = []; as a conditional statement, where I first check to see if cartItemsKey exists in global storage. If so, I will set cartItems = JSON.parse(localStorage.getItem('cartItemsKey'). Otherwise, I will set cartItems = [];.

    Thank you very much, @Alex Rasidakis, for your kind help.