Implementing a 1-second delay in a Vue.js delete request

I have items that are retrieved through API calls and users can add them to their cart. They also have the option to delete items from the cart, but I want the item to be visually removed from the front-end after 1 second because of an animation on the delete button. This is how my cart looks like:

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

When the delete button (bin icon) is clicked, the item should be deleted but I want it to visually disappear after a delay of 1 or 2 seconds. Here is the code snippet:

<template>
    <div id="delete-button"  @click.prevent="removeProductFromCart(item.id)">
        <input type="checkbox" id="checkbox">
        <div id="bin-icon">
            <div id="lid"></div>
            <div id="box">
                <div id="box-inner">
                    <div id="bin-lines"></div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import cartHelper from "../helpers/cartHelper";

export default {
    props: {
        item: Object,
    },
    data() {
        return {
            loading: false,
        };
    },
    methods: {
        removeProductFromCart(id) {
            cartHelper.removeFromCart(id, (response) => {
                this.loading = true;
                this.$store.dispatch('removeProductFromCart', {
                    cart: response.data,
                })
                setTimeout(() => this.loading = false, 1000);
            });
        },
    }
};
</script>

Even though I've set a timeout for 1 second, the item is being deleted immediately without waiting. Any ideas why this might be happening?

Answer №1

The issue lies in the fact that you are simply postponing the loading flag, without delaying the actual action itself. Try moving your dispatching action within the setTimeout function as well.

    eliminateItemFromCart(id) {
        cartHelper.removeFromCart(id, (response) => {
            this.loading = true;
            
            setTimeout(() => {
                this.$store.dispatch('removeProductFromCart', {
                   cart: response.data,
                })
                this.loading = false
            }, 1000);
        });
    }

Answer №2

Maybe consider postponing the execution of the method

deleteItemFromCart(id) {
    this.processing = true;
    setTimeout(() => {
        cartManager.removeFromCart(id, (response) => {
            this.$store.dispatch('deleteItemFromCart', {
                data: response.data,
            })
            this.processing = false
        });
    }, 1500)

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

When attempting to access the Object data, it is returning as undefined, yet the keys are being

I have an Object with values in the following format: [ { NameSpace: 'furuuqu', LocalName: 'uuurur', ExtensionValues: 0, FreeText: 'OEN', '$$hashKey': 'object:291' }, { Nam ...

Is there a way for me to dynamically incorporate new elements into this object?

I am working with an object msg.data that contains the following information: { "user_id": 1, "success": "true" } Now, I want to add a name field to this list: { "user_id": 1, "success": "true", "name" : "giri" } I have attempted the following ...

Encountering a JavaScript Error: "e is null" while utilizing assert for checking JavaScript alert text

I encountered a javascript alert in my program that I was able to interact with by reading the text and clicking on the buttons. However, when I tried to verify the alert text using assertequals function, I faced an error. Here is the code snippet: String ...

No Angularjs redirection without the "onload" event

In my search for a solution, I came across this answer but it did not quite fit my needs: Pass onload event through redirect The issue I'm facing is that I want the AngularJS section of my application to reload something when the user is redirected ...

What could be causing my function to exclude only the final element of the array when it returns?

My goal with the following code is to retrieve all items from item.children. However, I am puzzled as to why it's not returning the last item. After conducting multiple result logs and SQL verifications, I eventually pinpointed the issue in a specific ...

Guide on sending JSON object to Angular custom components

I have implemented a custom element in Angular 7 using the CUSTOM_ELEMENTS_SCHEMA. My app.module.ts code is as follows: export class AppModule { constructor(private injector: Injector) {} ngDoBootstrap() { this.registerCustomElements( ...

Why do query values disappear when refreshing a page in Next.js? [Illustrative example provided]

In my current project, I am developing a simple Next Js application consisting of just two pages. index.tsx: import React from "react"; import Link from "next/link"; export default function Index() { return ( <di ...

Verify if the keys are present within the object and also confirm if they contain a value

How can we verify keys and compare them to the data object? If one or more keys from the keys array do not exist in the object data, or if a key exists but its value is empty, null, or undefined, then return false; otherwise, return true. For example, if ...

Use Google Maps and MySql to retrieve specific markers within a designated radius using unique latitude and longitude coordinates

Can the latitude and longitude of specific coordinates within a certain radius be retrieved from a database? ...

Creating a "briefing" iframe at the top of a webpage

I'm looking for a way to allow users to embed my iframe at a specific size, like 100x100, and then have it resize dynamically to fit the page size when they click on it. I want this functionality to work regardless of how the HTML embedding the iframe ...

Unable to turn off X-Powered-By: Express

After attempting to use app.disable("x-powered-by"); without success, I came across some helpful posts on the topic: how to remove X-Powered-By in ExpressJS Can't get rid of header X-Powered-By:Express I am using "express": "^4.16.4" as backend a ...

When transferring the code to an exported function, it triggers a TypeError indicating a circular structure conversion issue when trying to convert

Experimenting with queries using the express and mysql packages, I encountered an issue when moving code to a different file for exporting. Initially, this code snippet worked without any problems: connection.connect(); connection.query('SELECT 1 + ...

Tips on utilizing these styles as properties for the Vue component

Is there a way I can incorporate these styles as properties for this component? <template> <div> <transition-group name='fade' tag='div'> ... </div> </te ...

What strategies can be employed to minimize redundant re-rendering of React components while utilizing the useEffect hook?

Hey everyone, I'm facing a challenge in my React/Electron project where I need to minimize renders while using the useEffect hook to meet my client's requirements. Currently, I have a container/component structure with an index.js file that house ...

Switch up the default font in your Nuxt 3 and Vuetify 3 project

I've been doing a lot of searching on Google, but I can't seem to find the solution. It seems like the challenge might be that the Nuxt 3 + Vuetify 3 combination isn't widely used yet? My current task is to implement a custom default font. ...

What is the best method for retrieving data from a specific collection in MongoDB?

Within the code snippet below, on the 4th line, 'Messages' is the name of my MongoDB collection that I created in another file. When I attempt to retrieve data from this collection, no errors occur. However, when I specify the name of a differen ...

Suggestions on how to refactor redundant code in various peer AngularJS controllers for handling $intervals

In my compact single-page application, I have implemented multiple tabs to display operational status information for different applications. Each tab is associated with a controller that creates $interval objects to make AJAX calls to fetch status data fr ...

Guide to designing a bar graph using HTML5 for a web app optimized for iPad

I am in the process of converting my iOS native app for iPad to a web app using HTML5. However, I am encountering an issue with creating a bar graph for the HTML5 app. Is there any documentation or built-in API available for this specific task? On iOS, we ...

Generate a new array of objects by cloning an existing array of objects with placeholder values

I am looking to transform an array of objects into another array of objects in order to generate a graph. Below is the array I am using to determine the position of each object within the new object. let uniqueSkills = ['Using', 'Analyzing ...

Develop a nodejs script to make a request using a curl or similar method

Can anyone help me figure out how to replicate the functionality of this OpenSSL command using Node.js or curl? The command is: openssl s_client api-prd.koerich.com.br:443 2> / dev / null | openssl x509 -noout -dates. I have been unsuccessful in my at ...