What is the most effective way to prevent actions while waiting for ajax in each specific method?

Within my JS component, I have various methods that handle events like click events and trigger ajax requests. To prevent the scenario where multiple clicks on the same button result in several ajax requests being fired off simultaneously, I typically use a flag. This flag is represented by a variable called working, which starts off as false. When an action is clicked, I set it to true, and once the ajax request is completed, I set it back to false. If working === true, I block any additional ajax requests.

The issue arises when working === true, as it blocks all actions within the component, preventing multiple actions from occurring at the same time. For example, a user can't click "save" until their previous "like" click has finished.

In the provided code snippet, respondToClickB would be halted until respondToClickA has been resolved.

I am seeking advice on how to improve the handling of this issue. Any suggestions are greatly appreciated!

export default {
    data: function() {
        return {
            working: false
        }
    },
    methods: {
        respondToClickA: function() {
            let self = this;
            if(!self.working)
            {
                self.working = true;
                axios.get('/ajax')
                    .then(function(response){
                        self.working = false;
                    });
            }
        },
        respondToClickB: function() {
            let self = this;
            if(!self.working)
            {
                self.working = true;
                axios.get('/ajax')
                    .then(function(response){
                        self.working = false;
                    });
            }
        }
    }
}

Answer №1

An interesting example of using Set: creating a Set object called self.working and adding/removing values to it.

Set functions similarly to an array, but it does not maintain order.

export default {
    data: function() {
        return {
            working: new Set()
        }
    },
    methods: {
        respondToClickA: function() {
            let self = this;
            if(!self.working.has('a'))
            {
                self.working.add('a')
                axios.get('/ajax')
                    .then(function(response){
                        self.working.delete('a');
                    });
            }
        },
        respondToClickB: function() {
            let self = this;
            if(!self.working.has('b'))
            {
                self.working.add('b');
                axios.get('/ajax')
                    .then(function(response){
                        self.working.delete('b');
                    });
            }
        }
    }
}

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

Retrieving data from a dynamic form using jQuery

Can someone assist me with the following issue: I have a dynamic module (generated by a PHP application) that includes input fields like this: <input type="text" class="attr" name="Input_0"/> <input type="text" class="attr" name="Input_1"/> ...

Adding and removing attributes with Jquery upon clicking a button

How can I make my listed items add an ID when clicked, or what am I doing incorrectly? $('.ex-menuLi #tt').attr('id', 'test'); $('.ex-menuLi').on('click', function(){ $(this).attr('id', &apos ...

The code in the head section is not running as expected

I've been exploring the possibilities of using lambda on AWS in combination with api gateway to create a contact form for a static S3 website, all inspired by this informative blog post: https://aws.amazon.com/blogs/architecture/create-dynamic-contact ...

Derive the property type based on the type of another property in TypeScript

interface customFeatureType<Properties=any, State=any> { defaultState: State; properties: Properties; analyzeState: (properties: Properties, state: State) => any; } const customFeatureComponent: customFeatureType = { defaultState: { lastN ...

Verify Session Cookies through JSONP requests

I've developed a bookmark that pulls all images from a webpage upon clicking and sends the image's src back to another server using JSONP. Challenge: The remote server must validate session authentication cookies to confirm that the user sending ...

Is JSON.stringify failing to function correctly in Mozilla Firefox?

Currently, I am attempting to convert an object into a string in javascript. After stringifying the object, I have noticed some discrepancies between different browsers. {"jobTypeArray":"[CONTRACT -W2]"} In Firefox and Chrome, the values appear as follow ...

Executing program through Socket.io alert

My NodeJS server sends notifications to clients when certain actions are performed, such as deleting a row from a grid. Socket.io broadcasts this information to all connected clients. In the example of deleting a row, one approach could be adding an `acti ...

Incorporating database row data into JavaScript objects: a guide

Here's a question that has me stumped and seeking help. Following an ajax send request, I utilized this php code to retrieve all the rows and columns from my database: $sql = "SELECT * FROM categories"; $result=$conn->query($sql); $arr = $resul ...

Discovering identical objects in two arrays in Angular using TypeScript is a breeze

I've hit a roadblock with a TypeScript problem in my Angular service. I have an array of ingredients: private ingredients: Ingredient[] = [ new Ingredient('farina', 500), new Ingredient('burro', 80), new Ingredient('ucc ...

To enhance the MUI v5 table row, simply apply a border when the mouse hovers

After working on creating a table with Material UI v5, I encountered an issue where I wanted to add a blue border to the table row when the mouse pointer hovered over it. I attempted several methods and did thorough research, but unfortunately, I was unab ...

The responsive navigation bar yielded an unforeseen outcome

Looking to create a responsive navigation bar similar to the one shown here My code successfully shows and hides the navigation items, but it's not updating the burger icon No console errors or warnings are present This is my HTML: <nav> ...

`On mouseup event, changing specific text`

I've been working on a real-time HTML highlighter that surrounds selected text with span elements containing a background property. Check out the fiddle here: https://jsfiddle.net/4hd2vrex/ The issue arises when users make multiple selections, leadi ...

Error with Chakra UI and React Hook Form mismatched data types

Struggling with creating a form using ChakraUI and React-Hook-Form in TypeScript. The errors seem to be related to TypeScript issues. I simply copied and pasted this code from the template provided on Chakra's website. Here is the snippet: import { ...

When using a function linked to an API request, an uncaught TypeError is thrown: Unable to access the 'includes' property of an undefined value

Utilizing the movie DB API (), I am displaying the results of my call on my page using Vue. The API supplies all the necessary data for me to achieve my objective, as demonstrated in this image https://i.stack.imgur.com/vP4I2.jpg Beneath each show's ...

The MongoDB object type is not stored

Let me share my customized user schema below. var userSchema=mongoose.Schema({ //name:{type:String}, username: {type:String, required:true, unique:true}, password: {type:String, required:true}, habit: {type:Object, required:true} }); Howev ...

What is the best method for integrating jQuery FullCalendar using AJAX?

I need assistance loading a full calendar using Ajax. The data will be passed from the controller in JSON format, but I am unsure of how to implement it. Can someone please help me with this? Here is my controller code: public function calenderHoliday(){ ...

Transferring temporary information from server to controller using angular-file-upload

Currently, I am utilizing the angular-file-upload library which can be found at this link: https://github.com/danialfarid/angular-file-upload. In the example provided on that page, data from a file is sent to the backend from a controller using the availab ...

The operation could not be completed with exit code 1: executing next build on Netlify platform

Having trouble deploying my Next.JS site to Netlify due to a build error. The site was working fine previously. Any suggestions on how to resolve this issue? 3:43:14 PM: - info Generating static pages (2/6) 3:43:14 PM: - info Generating static pages (4/6) ...

Although it may not be a constructor, the types certainly align perfectly

Although this question has been asked countless times before, none of these solutions seem to work in my case. Whenever I try to call the Config constructor, I encounter a TypeError: Config is not a constructor. Despite researching on Stack Overflow and M ...

Displaying website content within a pop-up dialog box

Currently, I am delving into the world of AJAX calls using jQuery.get() to dynamically load website content onto my HTML page. However, I have some doubts about whether I am utilizing this command correctly. As an example, I am trying to fetch data from a ...