Deleting Cart Items Permanently with AJAX in Vue.js and Shopify

Seeking assistance with implementing a feature to remove a product from a MiniCart using Vue.js in a Shopify theme. Below is the code snippet for minicart.liquid file along with the cart data stored in the 'data' property. Although the remove function successfully deletes the item, it reappears when the page is refreshed and the changes are not saved. Any guidance on resolving this issue would be appreciated.

I also attempted the following -

this.cart.items.splice(this.cart.items.indexOf(found), 1);
. This code successfully removes the object, but upon page refresh, the product reappears again in the cart.

<template v-if="cart">
    <li class="media" v-for="(item, index) in cart.items">
        <template v-if="item.image">
            <a :href="item.url">
                <img class="img-fluid mr-4 mb-2" width="150" :src="item.image" alt="">
            </a>
        </template>
        <div class="media-body">

            <h5 class="title"><a :href="item.url">${ item.product_title }</a></h5>

            <template v-if="!item.product_has_only_default_variant">
                <p>${ item.variant_title }</p>
            </template>

            <div class="price">
                <template v-if="item.original_line_price != item.line_price">

                    <span class="visually-hidden">{{ 'cart.label.discounted_price' | t }}</span>
                    ${ item.price | money }
                    <span class="visually-hidden">{{ 'cart.label.original_price' | t }}</span>
                    <span>${ item.original_price | money }</span>

                </template>

                <template v-else>
                    ${ item.price | money }
                </template>
            </div>

            <!-- Problematic function -->
            <span @click="remove(item)">${ item.original_price | money }</span>


            <div class="input-group quantity mt-3">

                <div class="input-group-prepend">
                    <span class="input-group-text" @click="decrement(item)">-</span>
                </div>

                <input type="text" v-model="item.quantity" class="form-control w-25" aria-label="Product quantity">

                <div class="input-group-append">
                    <span class="input-group-text" @click="increment(item)">+</span>
                </div>

            </div>

        </div>
    </li>
    data(){
      return {
        //The cart data stored in cartData.js
        cartData: store.state.cartData,
      }
    },
    methods: {
        //Remove item from the Minicart
        remove(item){
            let found = this.cart.items.find(product => product.variant_id == item.variant_id);

            if(found) {
                this.$delete(this.cart.items, this.cart.items.indexOf(found))
              
            }
        },

In an attempt to resolve the issue, I created a function to retrieve the variant_id and quantity, then pass it to the Shopify /cart/update.js API and delete the productInfo, but have been unsuccessful so far.

    removeFromCart(){
        let productInfo = this.cart.items.reduce(
          (accumulator, target) => ({ ...accumulator, [target.variant_id]: target.quantity}),
        {});
        console.log(productInfo);
        
        axios.post('/cart/update.js', {updates: productInfo})
        .then((res) => {
            this.$delete(productInfo)
        })
        .catch((error) => {
            new Noty({
                type: 'error',
                timeout: 3000,
                layout: 'topRight',
                text: 'Cart not updated'
            }).show();
        })
    },

Upon logging the productInfo, I can see the ID and quantity, but am unsure how to delete this onClick event.

Answer №1

Do you think it's correct that instead of using

<span @click="remove(item)">
, we should use
<span @click="remove(${item})">
?

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

Tips for updating checked checkboxes in a php mysql database

When submitting an HTML form with a selected checkbox, update the values of the selected checkboxes in a MySQL database. For example: update enquires set status = '2' where id in (selected checkbox values) View the screenshot of the checkbox Vi ...

Retrieving CSV information from several files within a JavaScript directory

Currently, I am attempting to retrieve data from numerous CSV files using 'csvtojson'. Firstly, I gathered an array of file names in a specific directory. Then, I used a forEach loop to extract data from various CSV files and convert it to JSON ...

When importing my Vue components using NPM, I can only locate the modules if they are situated within the src directory, rather than in the

Within my application's root directory, I have both a /node_modules/ and /src/ folder. After running npm install and installing packages using commands like npm install axios --save for all the required dependencies, I can see that they are being add ...

If a single checkbox is selected within a group, then every other checkbox should be deactivated and deselected

Here is the code snippet provided: function listen(element, event, callback) { if (element.attachEvent) { element.attachEvent('on' + event, callback); } else { element.addEventListener(event, callback); } } var form = document.que ...

Change XMLHttpRequest to jQuery for more efficient handling of data requests

I'm currently working on this code and looking to convert it into Jquery function GetServerTime() { var xhr; if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); ...

The actions performed within an event listener function are undone once they have been carried out

I'm a newcomer to Javascript and I am currently experimenting with it. While browsing through a tutorial on w3schools, I came across an example of changing the color of a button after clicking on it. My idea was to take it a step further by loading a ...

When a user connects to Node.js using sockets, the previous messages are loaded. However, a bug causes the messages to be loaded to all chat users, instead of just the

New to node.js, I am currently creating a chat application with two main files: server.js (server side) and script.js (client side). In the server.js file: socket.on('previousMessages', function (data){ db.query("SELECT * FROM messages", f ...

Issue with styled-components not being exported

Issue: ./src/card.js There was an import error: 'Bottom' is not exported from './styles/cards.style'. card.js import React from 'react' import { Bottom, Color, Text, Image } from "./styles/cards.style"; fu ...

The system displayed an 'Error' stating that the variable 'index' is defined in the code but is never actually utilized, resulting in the (no-unused-vars) warning

I have configured eslint and eslint-plugin-react for my project. Upon running ESLint, I am encountering no-unused-vars errors for every React component in the codebase. It seems like ESLint is not properly identifying JSX or React syntax. Any suggestions ...

Implementing Partial Login and Registration Views using AngularJS in conjunction with MVC5 and ASP.NET Identity

Embarking on the journey of creating a Single Page Application with log-in/register functionality using MVC5, ASP.NET Identity, and Angular feels like diving into a vast ocean of web development technologies. Despite being new to this realm, I delved into ...

JavaScript validation code for verifying hostnames with a specified domain name

I need a customized validation check for my order form where users are asked to enter their server hostname. The challenge is that I'm using WHMCS with encrypted PHP code and IonCube loaders, making it difficult to add this check. Users can input any ...

Executing CORS request using Node.js/Express and AngularJS

I've come across multiple responses on Stack Overflow claiming that setting response headers will resolve CORS requests. However, none of the solutions have worked for me. Here is the code I have implemented: //Server.js Code var express = require(&a ...

Error message indicating that the event "OnkeyDown" is not in sync within the React application

Hey everyone! I'm a beginner in web development and I'm struggling to understand why the event "OnKeyDown" is triggered the second time. My task involves changing (increasing, decreasing) parts of a date (day, month, year, hour, minutes, seconds) ...

Utilizing SlickGrid and DataView for calculating totals efficiently without the need for grouping

I am attempting to utilize Slick Grid and DataView to calculate column totals similar to the example shown here: . However, I do not want to group my rows. Therefore, I attempted not passing a getter and formatter into the dataView.setGrouping(..) method. ...

Encountered a 404 error while utilizing the Java - Angular web service

Encountering an error 404 in Firebug when attempting to send an object from Angular to a Java controller using JSON. While the backend in Java is able to receive the message, Angular is unable to find the specified path. Consequently, there is an issue wit ...

PHP form submission upon conditions being satisfied

I am not utilizing Javascript as it is disabled in my current environment. Here is the code that I would like you to review. I am attempting to use PHP to replicate the functionality of Javascript or jQuery's simple : document.form2.submit() <div ...

What is the method for tallying CSS page breaks in printed HTML documents?

Currently, for my report generation process using HTML and CSS to manage page breaks dynamically. I've enabled the option for users to print multiple reports at once by combining them into different sections within a single HTML document. This helps p ...

Encountering a "Error 404: Page Not Found" message when trying to request a json object from a node server

Working on a RESTful API, I have set it up to run on node.js using express.js, mongodb with mongoose for object modeling, and body-parser for passing HTTP data. However, whenever I start the server and try to access the specified IP address, I encounter a ...

Ways to verify the timeframe between two specific dates

Having two distinctive arrays: accomodation: [ { id: 1, name: "Senator Hotel Fnideq", address: "Route de Ceuta, 93100 Fnidek, Morocco", checkin: "September 1", fullCheckinDate: "2021-09-01", ...

Moving a Node project to a different computer

I am looking to transfer my Angular project from a Windows machine to a Mac. I attempted to copy the folder and run npm install, but encountered an issue. Here is the error message I received: sh: /Users/pawelmeller/Documents/hotel/angular4/node_modules/ ...