Should localStorage persist when application is run via live server?

mikekoscinski

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

mikekoscinski

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Where should a java application create files when it is run from Eclipse?

How can I persist localstorage when ComponentDidMount resets the value on refresh?

Which server should I choose when developing web application with NetBeans?

Persist localStorage with useReducer

Should a 14.04 server iso operate as a live CD?

Authentication error when calling Graph via Blazor Server application

Which PERSIST should I use in my Java Hibernate application?

Failed to create server socket when run flutter web application

Eclipse:Dynamic Web Application shows blank page when run on server

GitHub Pages website not running the same as when its run locally using live server

Dockerfile: changes made to filesystem via RUN do not persist

Run application in local server

PHP Slim 4 HttpNotFoundException -- Routes not found when moving application to live server

Deploying to live server via link on email notification

Should we need two servers to run ext js application with node.js at server side

How to run a .jsp file on a live server

How to separate Application Insights Live Streams by server?

Run X application in a Docker container reliably on a server connected via SSH without "--net host"

How to Run a GUI Application on Remote Server's X11 Display via SSH

Where should run-time unix sockets live on Linux?

React Persist State to LocalStorage with useEffect

Ionic localstorage doesn't persist

How to have localStorage data persist

Persist user theme in localStorage on reload

When outputting JSON content via Javascript, should I HTML escape on the server or client side?

Can i configure the Spring MVC application so that when ever i run the application, the controller or any method should be called automatically

How to use visual studio and google maps and show the map in full screen ? and when using live server to run how to open the same tab in the browser?

reset reducer state when application start while have persist state using redux-persist

@Username when run on server