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

The integration of a Bootstrap modal within the side bar's rendering

Struggling with a modal appearing inside my side div and can't find any solutions in the bootstrap5 documentation or online forums. https://i.stack.imgur.com/gHsBi.png I just want the modal to display centered on the page with the background fade ef ...

Leverage the power of AJAX and PHP to securely save comments for future

I have coded a JavaScript function that uses POST and GET methods to send comments from an input field and retrieve them when the page reloads. However, I am unsure of how to handle the data after it is sent in order to save it and access it again later. E ...

Issue arising during reconnection following a disconnection in the node-redis client

I'm struggling to understand why the SocketClosedUnexpectedlyError error is being triggered in the code snippet below: const redisClient = require('redis').createClient(); redisClient.connect().then(function() { return redisClient.disconn ...

When attempting to use nodejs's collection.find() method with MongoDB, no response is received

I have been struggling to develop a node.js script that can retrieve only the records with a specific string key-value pair from a MongoDB collection containing around 30,000 documents. When I run this query on my MongoDB server, it gives me the exact res ...

Is there a way to utilize a POST request to pass a React component from server.js to App.js for rendering?

I am new to React and JavaScript and still in the learning process :) I'm working on a magic 8 ball application where, upon clicking the button using the post method, I aim to retrieve a random answer (one of the 20 in my server.js) back to the same ...

Issue with a Jquery toggleClass function not working properly on hover

Hello everyone! I am a newbie in the community and relatively new to the world of web programming. I am encountering an issue that is really frustrating me. I attempted to use this code to add a class when hovering over the ul list element so that I can d ...

Do developers typically define all flux action types within a constants object as a common programming practice?

This question arises from an informative article on flux. The common approach involves defining all action types within a constants object and consistently referencing this object throughout the application. Why is it considered a common practice? What ...

Prevent the selection of a dropdown option in AngularJS once it has already

var demoApp = angular.module('myApp', []); demoApp.controller('QaController', function($scope, $http) { $scope.loopData = [{}, {}]; $scope.questions = { model: null, availableOptions: [ {id: '1& ...

Is it feasible to activate a Bootstrap Tooltip from a different element?

I am currently developing a system that enables users to add notes over an image they upload. Presently, I have a note div that, upon clicking, opens a text box for editing. When hovering over this div, I utilize Bootstrap Tooltip to preview the contents o ...

retrieving information from the database and passing it to the controller

I'm in the process of developing a new API with Express, following the MVC architecture. However, I've been facing difficulties getting the data to successfully return from the database access file to the controllers file. Initially, I attempted ...

Differences between ClosureFeedbackCellArray and FeedbackVector in the V8 engine

Can you explain the distinction between ClosureFeedbackCellArray and FeedbackVector within V8? What steps are necessary to initiate the shift from ClosureFeedbackCellArray to FeedbackVector? What is the significance of the InterruptBudget attribute found ...

Is Vuejs utilizing a customized event directive that does not require an event handler?

The code snippet below shows how fireCheck captures clicks on the list items (<li>) and toggles the enclosed checkbox. There is a click listener on the checkbox that prevents event bubbling up to parent elements, ensuring that the enclosing <li&g ...

Can you explain the significance of the regular expression in a dojo configuration file named dj

As I was working on developing dojo application modules, I came across a regular expression in tutorials. var pathRegex = new RegExp(/\/[^\/]+$/); var locationPath = location.pathname.replace(pathRegex, ''); var dojoConfig = { asyn ...

The distinction between storing data and component data becomes apparent when using Vuex in conjunction with a persisted state

Below is my post.js file in the store directory: import axios from 'axios' import createPersistedState from "vuex-persistedstate" export default { namespaced: true, state: { sample_data: 'Welcome!!', l ...

Incorporating components into a pre-existing webpage without utilizing npm

As a beginner in Vue.js and someone who primarily works in a traditional LAMP environment, I have noticed that the vue components I've attempted to use are not working as expected. Can anyone assist me with: Offering guidance on installing vue compo ...

Steps to reveal a div when a button is clicked within a v-for loop using VueJS

Context In my code, I am utilizing a v-for loop to display sets of buttons and corresponding input fields. Each button is supposed to trigger the display of its respective input field upon being clicked. Issue However, the problem arises when the button ...

The jquery selector fails to retrieve all elements

On the upcoming web page, I am attempting to use Jquery to select all <li> elements. Specifically, I want to target all the products contained within <ul class=search-result-gridview-items">. You can find the products here: I have made attempt ...

Tips for muting console.log output from a third-party iframe

As I work on developing a web application using NEXT.js, I am encountering an issue with a third party iframe that is generating numerous console logs. I am seeking a way to silence these outputs for the iframe. The code in question simply includes an < ...

Issue encountered: Trying to deploy firebase functions and hosting with vue-cli v3 and node.js leads to an error "No npm package found in functions source directory

My plan is to utilize Vue.js for the Frontend and Firebase Functions (Express.js) + Firestore for the Backend. Step 0: I initiated a new project on Google Firebase, then created a new Service Account with Owner's permissions to be used with Admin SDK ...

Encountered a SyntaxError: Unexpected token "e" while attempting to parse a JSON string

When I attempt to use JSON.parse in order to convert the string below into a JavaScript object, I encounter an "Uncaught SyntaxError: Unexpected token e" error. { "__type": "HRIS.oHRData, HRIES, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", ...