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

Determine the coordinates of the mouse cursor within a specific div element

Similar Questions: Determining Mouse Position Relative to a Div Getting the Mouse Position Using JavaScript in Canvas Is there a way to retrieve the mouse position within a canvas element with fixed dimensions and automatic margin? I am unable to ...

Initiate the Bull Queue Process upon launching the Application

As I develop my API, I am setting up a queue and adding jobs to it. Additionally, I have configured the API to start processing these jobs as soon as they are added. const newQueue = createQueue(queueName, opts); newQueue.add('JokesJob', data, o ...

Prevent Click Event in JQuery

I have a requirement to disable all click events on my webpage. However, even after using the appropriate code to prevent these events from firing, some of them are still getting called. Let me explain with an example. <div id='parent'> ...

Utilize Shopify's API to seamlessly collect email inquiries directly through a custom contact page

Currently, I am facing a challenge in making my contact us page functional within my Shopify app. The link provides guidance on creating a contact page in Shopify, but as I am developing a Shopify app using nextjs, I am struggling to integrate my own co ...

Why is the jQuery change event only firing when the page loads?

I am experiencing an issue with a .js file. The change event is only triggering when the page loads, rather than when the selection changes as expected. $(document).ready(function(){ $("#dropdown").on("change keyup", colorizeSelect()).change(); }); f ...

Sloped Divider on the Upper Edge of the Page

I'm currently in the process of developing a new website, and I'm looking to create a unique design for the main navigation bar on the homepage. Here is the ideal layout that I have in mind: https://i.stack.imgur.com/pc8z4.png While I understan ...

Can you explain the concept of themes in Material UI?

I am trying to wrap my head around the concept of themes and what they are meant to represent. I have gone through the documentation, but I still find it confusing. For instance, here is a snippet of code that I am referring to. I just want to understand ...

Is there a way to change the color of just the most recently clicked anchor element <a>?

I have a sidebar with anchor elements (Link 1,2,3 in my HTML). I want the text color of these anchors to change when clicked. Additionally, I need only one anchor element to be colored at a time, meaning the previous one should return to its normal color. ...

Adding AJAX functionality to voting buttons and updating the results container can enhance user experience and streamline the

I'm currently working on integrating Facebook-like interactions with voting buttons on my reviews page. Here's the code snippet I have so far: % @school_reviews.each do |school_review| %> <div class="widget-box "&g ...

Updating or swapping images using JavaScript and HTML

I am looking to implement a feature similar to Twitter, where uploading a picture automatically updates the avatar by displaying a spinner while the new image loads. I attempted to accomplish this with the following code: <script language="javascript"& ...

When a user focuses out of a field, an event object will appear within it

Currently, I am developing a VueJS application that enables users to modify JSON files containing specific data. In my project, I have implemented two similar components: AliasEntry and EquipmentEntry. The latter is responsible for manipulating an array of ...

Implementing automatic dark mode activation during nighttime with jQuery or JavaScript

I'm looking to implement an automatic dark mode feature on my website that switches on at night and off during the day or morning. Currently, my website has a dark mode toggle code that allows users to switch between dark and light modes using local ...

Is the Spring MVC ModelAndView object being returned?

After clicking a link on a jsp page, I have a GET method that is instantiated as: HTML: <div class="panel accordion clearfix" id="dispdir"> <script type="text/javascript"> window.onload = function() { //showDirectorySe ...

Navigating a parameter within an AngularJS directive

I am currently developing a directive that acts as a wrapper for the freebase search widget using jQuery. This is my first attempt at creating a directive and I have encountered some challenges. Here are the functionalities I am aiming for: 1. The ability ...

Updating $data within a VueJS directiveIs there something else you

We have a component and a directive. The structure of our component data is as follows: { langs: [ { title: '', content: '' }, { title: '', content: ...

Can Sequelize be used to perform queries based on associations?

I have designed a data structure that includes an n:m relationship between "Rooms" and "Users." My current goal is to remove or delete a room. To accomplish this, I need to verify if the user initiating the deletion process is actually present in the room ...

I am interested in verifying the presence of a user

Below is the form for checking user existence using AJAX: <!DOCTYPE html> <html> <head><title>Register new user!</title> <script src="jquery-1.7.1.min.js"></script> </head> <body> ...

Tips for preventing my component from being duplicated during the development process

I found a helpful guide on creating a JavaScript calendar in React that I am currently following. After implementing the code, I successfully have a functional calendar UI as shown below: // https://medium.com/@nitinpatel_20236/challenge-of-building-a-cal ...

Using JQuery to register click events for elements that have been dynamically added to the

Within a div bearing the class c, I'm updating its content dynamically using Ajax. The end result is something like this: <div class="c"> <div class="del" id="1"></div> <div class="del" id="2"></div> <div class= ...

In React JS, the data from my response is not being saved into the variable

My goal is to store the response data in the variable activityType. Within the useEffect function, I am iterating over an API based on the tabs value. The API will return a boolean value of either true or false. While I can successfully log these values ...