"Encountered a problem while attempting to remove an element from

Currently, I am attempting to remove individual items from the cart that is stored in localStorage. However, I have only been successful in deleting the entire array using methods like removeItem() or clear(). My goal is to delete specific items based on their id. When trying to use the splice method, I encounter an error. As I am still learning, please let me know if more information is needed.

deleteProduct: (index) => {
            const existingEntries = JSON.parse(localStorage.getItem("cartData"));
            existingEntries.splice(index, 1);
            localStorage.setItem("cartData", JSON.stringify(existingEntries));
        }
let cartData = window.localStorage.getItem('cartData');

const cart = {
    state: {
        cartData: cartData ? JSON.parse(cartData) : {
            foods: [],
            totalPrice: [],
            Quantities: []
        },
    },

https://i.sstatic.net/j5yeW.png

https://i.sstatic.net/Yasb1.png

Answer ā„–1

Important details:

  1. The variable cartData contains a string and is stored in the browser's localStorage as a string.
  2. Once you parse it, cartData becomes an Object data type.
  3. Within cartData, there is an array called foods which holds various food items.

Steps to follow in code:

  1. Retrieve the cartData from the localStorage.
  2. After parsing it, you will have a JSON Object with the key named 'food'.
  3. Access the 'foods' key within cartData object.
  4. Perform any necessary operations on the 'foods' array like splicing.

Answer ā„–2

Would you be willing to give this a shot?

let shoppingCart = JSON.parse(localStorage.getItem("shoppingCart"))
if(shoppingCart && shoppingCart.items) {
    const itemsInCart= shoppingCart.items;
    itemsInCart.splice(index, 1);
    localStorage.setItem("shoppingCart", JSON.stringify(itemsInCart))
}

Don't forget to update the totalPrice and Quantities before saving.

Answer ā„–3

It's a good practice to parse your array once it's retrieved

removeItem: (position) => {
        var cartData =  localStorage.getItem("cartItems")
        const items = JSON.parse(cartData);
        items.splice(position, 1);
        localStorage.setItem("cartData", JSON.stringify(items));
    }

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

JavaScript - Populating Dropdown Menu with Fresh Information

I'm attempting to populate a combobox (input) with data fetched via AJAX. The goal is to display every city associated with a selected state, chosen from another select control (the state control). My Attempt: I've implemented the "change" even ...

Unable to locate the value property of a null object

I'm currently working on creating a Shopping Cart using HTML, CSS, JavaScript, and JQuery. The idea is that when you click "Add to Cart" for the orange item, most of the HTML elements will disappear, leaving only the table displaying the Shopping Cart ...

Populate a secondary dropdown menu using the selection from a primary dropdown menu and retrieve the corresponding "value" instead of displaying the value as a dropdown option

I am attempting to create two dropdowns that are populated by another dropdown. Below is the code: HTML: <form type=get action="action.php"> <select name="meal" id="meal" onChange="changecat(this.value);"> <option value="" disabled select ...

Authenticating Users with Laravel and Vue.js

In my Vue.js application, I have implemented a login system. The main script in my main.js file includes the necessary imports and configurations: import Vue from 'vue'; import NProgress from 'nprogress'; import Resource from 'vue ...

Can one recover a Javascript file from a server?

In Python, I am able to extract Javascript code from an HTML file using the code snippet below. import urllib2, jsbeautifier from bs4 import BeautifulSoup f = urllib2.urlopen("http://www.google.com.ph/") soup = BeautifulSoup(f, "lxml") script_raw = str( ...

Simply modifying a custom attribute source using jQuery does not result in it being refreshed

Introduction: Utilizing jQuery.elevateZoom-3.0.8 to display zoomed-in images. The SRC attribute contains the path to the smaller/normal image The DATA-ZOOM-IMAGE attribute holds the path to the larger image used for zooming. Here is the HTML Code: ...

Implementing a file download feature in Python when clicking on a hyperlink

I'm attempting to click on the href link below. href="javascript:;" <div class="xlsdownload"> <a id="downloadOCTable" download="data-download.csv" href="javascript:;" onclick=&q ...

Understanding how to monitor a Boolean value that fluctuates in real-time within a three.js

Currently, I am working on developing a 3D 4x4x4 tic tac toe game using three.js. In order to determine the win condition for combinations, I have created a boolean array. With a total of 64 blocks (16*4), I have initialized a boolean array of size 64 with ...

JavaScript function to divide arrays into sequences

I have an array that looks like this: var arr = [12, 13, 14, 17, 18, 19, 20] I'm trying to figure out how to iterate through this array and split it into two arrays based on sequences. Essentially, if i+1 != true, I want to create a new array. var ...

The attribute 'getTime' is not found in the data type 'number | Date'

class SW { private startTime: number | Date private endTime: number | Date constructor() { this.startTime = 0, this.endTime = 0 } start() { this.startTime = new Date(); } stop() { this.endTim ...

The Ajax response is coming back with a null value, but upon inspecting the network response

I'm facing a strange issue where one specific value from an ajax json response is showing up as an empty string, while all other values are appearing correctly. An unusual aspect of this problem is that the network panel displays the correct value in ...

Having difficulty processing information retrieved from an ajax request in jQuery

Upon making a request to the server and converting the retrieved data into a table format, I utilize jQuery's .html() function to display it on the webpage. However, despite the data being visible on the page, I encounter issues when attempting to man ...

An issue occurred when attempting to modify bookings with the setState function

When working inside the deleteBaseBooking function, my goal is to use setState to set this.state.checkIndexStatus[key] = null. However, I am encountering an error: deleteBaseBookings(){ for(var key in this.state.checkIndexStatus){ if(t ...

Type of object is unidentified in Vuejs with Typescript error code ts(2571)

Currently, I am facing a challenge with storing JSON data in a variable within my Vue project. Below is the code snippet used to upload and store the file: <input type="file" id="file" ref="fileSelect" class="custom- ...

I am finding the event naming conventions in Vue 3 to be quite perplex

In the parent component, there is a child component: <upsetting-moment-step :this-step-number="1" :current-step-number="currentStepNumber" @showNextStep="showNextStep" ></upsetting-moment-step> The par ...

Moving a Ball Back and Forth Using Three.js

Iā€™m looking to create a continuous motion for a Ball in Three.js, where it moves to the right, returns to its starting position, and then repeats the sequence. var geometry = new THREE.SphereGeometry( 5, 32, 32); var material = new THREE.MeshPhongMateri ...

Switching from Vanilla JS to Vue.js, dealing with querySelector problems

Seeking assistance with transforming the following CodePen example to a Vue.js component: https://codepen.io/kjbrum/pen/qooQJJ While attempting to incorporate this.$nextTick for handling DOM manipulation, I'm encountering challenges in making it func ...

What are some ways to divide drop targets with React DnD?

In my React Dnd v16.0.1 project, I am dynamically rendering containers and images from JSON data using map function. The issue I'm facing is with two droppable containers where only one should accept dropped images. However, when I drop an image on th ...

Tips for Successfully Capturing Form Data with OnChange Event

On my website, I have set up a dedicated page for testing the functions I have developed, totaling around 30 to 40 so far. I have implemented a drop-down menu to list out these functions by name. When a function is selected, I trigger it using onChange wit ...

Redirecting based on GeoIP location after the DOM has completely loaded

Below is a JavaScript snippet that redirects based on GEOIP : <script type="text/javascript"> // Function to call FreeGeoIP after page load function newyorkGeoIP() { var script = document.createElement('script' ...