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

Using the Google Chrome console, execute a command on each page within a specified website

While browsing a website, I noticed a bug that required me to manually run a JavaScript function each time I navigated to a different page in order for the site to work smoothly. Is there a way to automate this process upon page load? I am using Google C ...

Prevent typing in text box when drawer is activated by pressing a button

update 1 : After removing unnecessary files, I need assistance with https://codesandbox.io/s/0pk0z5prqn I am attempting to disable a textbox. When clicking the advanced sports search button, a drawer opens where I want to display a textbox. The toggleDra ...

What is the method to conceal a certain element in jQuery based on the value of another element?

I am dealing with the following HTML structure: <button id="hideToggle">show/hide</button> <form id="item"> <div>Item 1 <input name="item1" type="number"/></div> <div>Item 2 <input name="item2" type="nu ...

Trigger the postback URL using a different button

I am trying to achieve a functionality where I have two buttons: ButtonA (normal) and ButtonB (with a postbackurl). What I want is for ButtonB to be executed when ButtonA is clicked. <asp:button ID="ButtonA" runat="server" text="Button" /> <asp: ...

The existence of useRef.current is conditional upon its scope, and it may be null in certain

I'm currently working on drawing an image on a canvas using React and Fabric.js. Check out the demo here. In the provided demo, when you click the "Draw image" button, you may notice that the image is not immediately drawn on the canvas as expected. ...

How to append a JSON object to an existing .json file

UPDATE: Despite successfully executing the PHP code, my JSON file remains unchanged. I must apologize in advance for covering old ground, but I have spent countless hours exploring different solutions with no success. Perhaps sharing my challenge could as ...

rating-widget not displaying when performing an ajax request

Having an issue with the star rating plugin () while using an ajax function for searching and filtering. The star rating displays correctly when the page initially loads https://i.stack.imgur.com/eaOmu.png However, when utilizing the filter and search fu ...

Develop a PHP Ajax jQuery UI Progressbar to track the progress of a lengthy MySQL task

My PHP script is taking a long time to run due to frequent SOAP calls to another website. I want to add a progress bar to track the completion percentage of this operation. I think the best approach is to use asynchronous Ajax calls to execute the PHP scr ...

What is the process of replacing fetch with JavaScript?

Looking to test my React application and mock the backend calls, I made the decision to swap out fetch with a Jest function that returns a static value. The issue I encountered was my inability to override the default fetch behavior. After some research, ...

Enhance your user interface by adding a tooltip above a button

I am currently working on creating a button that can copy content from a variable into the clipboard using TypeScript and Material-UI. Here is what I have tried: const [copySuccess, setCopySuccess] = useState(''); const copyToClipBoard = async ( ...

What is the best way to pick out specific passages of text

I'm attempting to create an autocomplete feature where the data is displayed in a div below the text box as the user types. While this typically involves ajax, I've simplified the approach without using jQuery autocomplete. Once the text appears ...

What is the best way to have a button activate a file input when onChange in a React application?

Having an input field of file type that doesn't allow changing the value attribute and looks unattractive, I replaced it with a button. Now, I need the button to trigger the input file upon clicking. How can this be achieved in React? Edit: The butto ...

The integration of Angular 6 with AngularJS components fails to load properly in a hybrid application

Currently, I am in the process of upgrading a large AngularJS version 1.7.3 to a hybrid app using Angular 6. The initial phase involved converting all controllers/directives into an AngularJS component. Subsequently, I created a new Angular 6 project skele ...

Unable to invoke the Spring controller while using ajax

I am facing an issue while using Ajax with Spring. My requirement is to filter a list of results based on the region selected from a drop-down or the store name entered on the screen. To achieve this, I thought of using Ajax. However, I am unable to call ...

Exporting Typescript to Javascript files

I have created a sample TypeScript object with the following code: declare const S3 = "https://s3.amazonaws.com/xxx/icons"; declare const SVG = "svg-file-icons"; declare interface MyIcons { "image/jpeg": string; "image/jpg": string; } export const F ...

Eliminating unnecessary whitespace between the bottom of the document and an element

I have a HTML page that when scrolled should limit scroll to the document height. It must not exceed the bottom of an element. Here is a screenshot for better understanding: https://i.stack.imgur.com/RaVg8.jpg The scrolling should be limited after the En ...

What could be causing the malfunction in my 'sort' function? I have thoroughly checked for errors but I am unable to locate any

Exploring the world of JavaScript objects to enhance my understanding of functions and object manipulation. I have created a program that constructs an Array of Objects, each representing a person's 'firstName', 'middleName', and & ...

Refreshing Django HTML table dynamically upon database updates

Currently, I have an HTML table set up using a Django template to showcase data from my database. I am looking to ensure that this table remains updated in real-time whenever the database undergoes changes. Despite my research efforts, there is limited inf ...

What is the best way to smoothly transition between website pages while maintaining continuous music playback with AJAX?

Is it possible to smoothly transition between pages on a website without interrupting the music using AJAX? 1. Start playing the music from "https://example.com/music" 2. The music continues to play 3. Navigate to another page (e.g. "https://example ...

Enhancing serialized form with additional information through an ajax request

I'm currently facing an issue with adding additional data to my serialized form string. The situation is that I have a form with a set of fields called "Services", and users are able to add as many services as they want dynamically using a button in t ...