Avoid accidental overwrites in localStorage using JavaScript

I've been working on a Vue project where I'm implementing a shopping cart feature. In this setup, when the user clicks on a button, the item details are stored in localStorage and then displayed in the shopping cart interface.

However, I encountered an issue where pressing on a new product to add it to the cart resulted in my key being overwritten. Consequently, I could only have one item in the cart at a time.

Snippet of relevant code:

addToCart() {
    var size = this.selectedSize;
    var color = this.selectedColor;
    let newItem = {size: size, color: color, name: this.getProductDetails(this.productLinks).name, id: this.getProductDetails(this.productLinks).id};
    this.cartItems.push(newItem);
    localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(this.cartItems));
}

Answer №1

addToCart() {
  const item = {
    size: this.selectedSize,
    color: this.selectedColor,
    name: this.getProductInfo(this.productLinks).name,
    id: this.getProductInfo(this.productLinks).id,
  };
  this.cartItems.push(item);
  const currentItems = localStorage.getItem(CART_STORAGE_KEY) || '[]';

  localStorage.setItem(
    CART_STORAGE_KEY,
    JSON.stringify([...JSON.parse(currentItems), ...this.cartItems])
  );
},

This approach should function correctly, but it may not be the most efficient solution. It would be more appropriate to load cart items from localStorage when the relevant component is initialized.

created() {
  const currentItems = localStorage.getItem(CART_STORAGE_KEY) || '[]';
  this.cartItems = JSON.parse(currentItems);
},

With the cart now in sync with localStorage, you can simplify your toBasket() method:

toBasket() {
  const item = {
    size: this.selectedSize,
    color: this.selectedColor,
    name: this.getProductInfo(this.productLinks).name,
    id: this.getProductInfo(this.productLinks).id,
  };
  this.cartItems.push(item);
  localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(this.cartItems));
},

Extra Credit:

Consider using Vuex to manage your cart items and utilize the npm package vuex-persisted-state for automatic synchronization between the Vuex cart module and localStorage.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a Regular Expression that excludes all white spaces, including those at the start or end of the string

I attempted to implement this solution, however, I am encountering some issues: Click here to see the demo <form name="myform1"> Valid? {{ myform1.$valid }} <input type="text" name="username1" ng-model="username1" ng-pattern="/^\S.*?&bso ...

Challenges with handling JSON data in JavaScript

I am currently attempting to retrieve and parse JSON data in order to display it on a blank HTML file. Unfortunately, I keep encountering an issue where if I retrieve and parse the data, I receive an error stating Uncaught TypeError: Cannot read property & ...

Difficulty with info window within a for loop

I am currently working on implementing multiple info windows for markers. I found an example on Stack Overflow that I am trying to follow. Despite not encountering any errors in the console, the info windows do not appear as expected when clicking on the m ...

Having difficulty changing the value of a Select element in AngularJS

Struggling to update the select value from AngularJs. Check out my code below: <select ng-model="family.grade" > <option ng-repeat="option in options" value='{{option.id}}'>{{option.text}}</option> </s ...

Error event triggered by Ajax call despite receiving 200 ok response

$.ajax({ url: 'http://intern-dev01:50231/api/language', type: 'GET', dataType: 'json', success: function() { console.log('Success! The call is functioning.'); }, ...

Extract website addresses from a text and store them in an array

I am currently attempting to extract URLs from a string and store them in an array. I have implemented a node module to assist with this task. const getUrls = require("get-urls") url = getUrls(message.content) However, the current implementation fails to ...

The Bootstrap Mobile Navigation transition is not displaying as intended in my CSS coding

On both desktop and mobile screen sizes, I have a white navigation bar. However, for the mobile dropdown menu, I want the background to be grey. I managed to achieve this by targeting .show on smaller screens in the CSS and specifying the grey background ...

An exploration on integrating a controller into an Angular directive class using Typescript

Here's the TypeScript code for an Angular directive class I've been working on: I'm wondering how I can incorporate a controller into this directive without creating a separate controller class. My goal is to write and inject the ISOLATE SC ...

Formatting specific elements within an array

I am working with an array of names, some of which are repeated. These names are then split in half and displayed as li. One thing I am struggling to figure out is how to style the name Joeyc with text-decoration: line-through; on all instances of .book w ...

What is the best way to extract an object from an array that only includes one element, and that element is an object?

Here is the output of my updated function: db.collection('SOCIAL').get().then((snapshot) =>{ snapshot.docs.forEach(doc => { tempData.push(doc.data()) }) return tempData }) I want to store these valu ...

AngularJS Get request unable to fetch image URL due to receiving a "302 found" error

Trying to enhance my AngularJS app by incorporating an image from a random cat image site, using the URL received. Below is the snippet from my controller.js: 'use strict'; /* Controllers */ var catPath = "http://thecatapi.com/api/images/get? ...

Utilizing node-json2html, generate individual HTML tables for each record

I need assistance in consolidating my JSON data into a single HTML table, instead of generating separate tables for each record through my current transformation process. var data=[{"name":"aa","mid":"12345","user":"a123","password":"a@123"},{"name":"bb" ...

Cookies are strangely absent from the ajax call to the web api - a puzzling issue indeed for Web Api users

Hello, here is the code I'm working with using Ajax: function GetCurrentUserId() { return $.ajax({ type: "GET", url: rootUrl + '/api/Common/CurrentDateAndUser', dataType: 'json', ...

Are you familiar with manipulating the JSON data array retrieved from an Ajax response?

Is it possible to handle a response from AJAX request in PHP? I'm not very familiar with JavaScript, so I'm struggling with this one. This is what I have managed to put together: var base_url = 'http://dev.local/westview/public'; $(& ...

Utilize Javascript and JQuery to implement sending a custom header in an OPTIONS preflight API request

Snippet: $.ajax({ type: 'GET', dataType: 'json', url: api, xhrFields: { withCredentials: true }, beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', "Basic [my auth token]"); }, ...

Having trouble sending data from a page to a child component using getStaticProps

I'm currently working on a project using next.js and I'm facing an issue with passing data from the "gymlist" page to the "table" component. Here is the code snippet from the "gymlist" page where I have defined the getStaticProps function: expor ...

Issue with serving static files in ExpressJs

I'm facing an issue with my Express app where the static files are not working properly for certain routes. For example, when I visit '/', all styles and images load correctly as expected when the index.ejs is rendered. However, when I navi ...

Exporting JavaScript formatting in Netbeans is a breeze

Does anyone know how to preserve the formatting for JavaScript in Netbeans 8.1 when exporting? After clicking on the export button and expanding Formatting, I couldn't find any option specifically for JavaScript. I've thought about locating the ...

Error: 'require' function is not recognized in the latest JavaScript file

I am interested in using anime.js. To install this library, I need to follow these steps: $ npm install animejs --save const anime = require('animejs'); The code should be written in a js file named "anime.js" Here is the code for "anime.js": ...

Create a duplicate of the prop object by transferring it to a fresh data

Structure of Vue components; UserList.Vue (parent component) UserEditor.vue (child component) A table displaying users is present, when a user is selected, the selectedUser property is updated with the chosen user (within UserList.vue); selectedUser: ...