The proper method for updating data on a backend API using Axios and Vue

I am working on a Vue application that includes several form fields. I want to ensure that any changes made by the user are saved in real-time to a backend database using a REST API with Axios, without requiring the user to click a save button.

I have two queries regarding this:

#1: Which event should I monitor to trigger my API calls?

Is it appropriate to use a v-on:change binding, or would this event be triggered too frequently (with every keystroke)?

<input type="text" v-model="userName" v-on:change="signalChange">

methods:{
     signalChange: function(evt){
        axios.put(this.getRootURL + 'app/save.php', {
        recordId: this.$route.params.recordid,
        userName: this.userName
      }).then(response => {
        console.log("Change saved...")
      }).catch(e => {
        console.log("Error... ")
    }
}

#2: Is it necessary to queue changes to ensure that the last change is saved properly?

For example, if a user quickly toggles a button back and forth, there might be a delay due to the asynchronous nature of Axios, causing the last change to not be saved last on the server. This could lead to a discrepancy between the UI and backend data.

Would it be advisable to create a Sync utility that stores changes in a queue array and waits for each change to complete before sending the next one to the server? Are there any existing libraries or code samples available for this purpose?

Thank you!

Answer №1

To enhance the process, consider implementing a timeout period to await additional changes. If no further adjustments are made within the specified time frame, proceed with saving the modification.

Monitoring the change event is effective. Alternatively, you can also utilize the input event.

The code sample provided below addresses both of your inquiries:

HTML/Template

<input type="text" v-model="userName" v-on:change="waitToSave">

JavaScript:

export default {
  data(){
    return {
      /* other relevant data */
      timeout: null,
      waitTime: 1000  // 1 second, or adjust as needed
    }
  },
  methods:{
    waitToSave: function(){
      clearTimeout(this.timeout);
      this.timeout = setTimeout(this.signalChange.bind(this), this.waitTime);
    },
    signalChange: function(){
      axios.put(this.getRootURL + 'app/save.php', {
        recordId: this.$route.params.recordid,
        userName: this.userName
      }).then(response => {
        console.log("Modification saved...")
      }).catch(e => {
        console.log("An error occurred... ")
      });
    }
  }
}

If the timeout suffices for your scenario, employing a queue might not be necessary as previously mentioned.

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

Having trouble with axios calls being caught in the catch block when mocking it in Jest

When my component loads, the useEffect function triggers an axios.get request to fetch user data and displays it on the page. However, I'm having trouble replicating this behavior in Jest. Every time I try, I end up in the catch block and the data ke ...

Firebase web authentication is most effective upon the second attempt

I am currently working on a website that interacts with Google's firebase to read and write data. The website has both anonymous and email authentication enabled. Users can view the data anonymously, but in order to edit or write new data, they must s ...

How can I properly implement a Closure or IIFE to manage an onclick event in ReactJS?

I'm encountering an issue while attempting to utilize the this object in an event handler. An undefined error related to the this object keeps popping up. My development stack includes ReactJS and Redux as well. class Chat extends Component { c ...

Npm is unable to locate the package.json file in the incorrect directory

Hello, I am currently in the process of setting up webpack. I have all the configurations ready, but when I attempt to execute webpack in my terminal, it looks for the package.json file in the incorrect location. Is there a way for me to modify the path ...

How to send props from a Vue.js component tag in an HTML file

I'm facing an issue with passing props from the HTML to the JavaScript code and then down to a Vue component. Here's a snippet of my index.html file: <div id="js-group-discounts"> <div class="form-group required"> <datepick ...

Creating a table with a static first column and vertical text positioned to the left of the fixed column

To create a table with the first column fixed, refer to this fiddle link: http://jsfiddle.net/Yw679/6/. You also need a vertical text to be positioned to the left of the fixed column in a way that it remains fixed like the first column. The disparities be ...

Tips for transforming a container div into a content slider

Working with Bootstrap 3, a custom div has been created as shown below: <div class="second-para"> <div class="container"> <div class="second-section"> <div class="c ...

Asserting within a specific condition's scope in TypeScript

I am facing a similar situation, type Field1Type = { a: string; } type Field2Type = { b: string; c: number; } type ObjType = { field: Field1Type | Field2Type } const field = { b: "" c: 0 } const obj = { field } as ObjType i ...

Ensuring that EJS IF/ELSE statements are evaluated accurately

I am encountering an issue where my variable 'answer' is returning the string 'success' and displaying correctly in the view. However, the IF/ELSE statement always seems to evaluate to the ELSE condition and displays 'no' inst ...

Can I trust the security of my credentials if they are able to be logged in the console

While working with NextJS, I've encountered a challenge in applying server-side rendering methods like getStaticProps to maintain credentials on the server rather than exposing them to the client. Despite my attempts, I couldn't find a straightfo ...

Is it possible to display a title tooltip only when the CSS ellipsis feature is active in a React component?

Issue: I am trying to find a neat solution to display a title tooltip on items that have a CSS ellipsis applied, within a React component. Approaches Attempted: I created a ref, but it only exists after componentDidUpdate. Therefore, I force an update w ...

Having trouble with sending a post request through ajax

Whenever I try to initiate an Ajax request upon clicking a button, the request never seems to get executed. Below is the snippet of my HTML code : <!DOCTYPE html> <html lang="en"> <head> <title>User Form</title> ...

Delaying UI interactivity until the document is fully loaded

I'm currently developing a web application that must be compatible with Internet Explorer 8 (yes, you read it right, compatible with the HELL). The issue I'm facing is with uploading a file which is later processed by PHP code and then refreshes ...

The typescript error TS2339 is triggered by the property 'webkitURL' not being found on the 'Window' type

Currently utilizing Angular 2 in a project that is compiled with TypeScript. Encountering an issue when attempting to generate a blob image: Error TS2339: Property 'webkitURL' does not exist on type 'Window' The TypeScript code causi ...

What is the reason for jQuery returning an integer instead of an object?

Currently, I am attempting to preselect an option within a <select> tag based on a variable. However, while using jQuery to select the elements and iterating through them with .each(), it appears to be returning integers instead of objects, making .v ...

Identify the credit card as either American Express or American Express Corporate

My JavaScript code can successfully detect credit card types, but I have encountered an issue. I am unable to differentiate between American Express and American Express Corporate cards. Is there a way to distinguish them or is it impossible to identify wh ...

What exactly is Bootstrap - a CSS framework, a JavaScript framework, or a combination

Being new to Bootstrap, I have taken the time to explore What is Bootstrap? as well as http://getbootstrap.com/. From what I understand so far, Bootstrap is a CSS framework that aids in creating responsive designs that can adapt to various devices. Essent ...

"Learn the trick to replace the Ctrl + N shortcut in Firefox and initiate an AJAX request

Note: The answer provided by Juan Mendes has been selected as the best answer for my situation due to its usefulness. AxGryndr also offered valuable information, so I recommend reading both answers as they are beneficial in different scenarios. Thank you t ...

Displaying default value in select dropdown using v-model

I am working on a Vue selectbox with an initial v-model value, and I want to display its value on the selectbox. However, I am unsure of how to accomplish this. Any assistance would be greatly appreciated. new Vue({ el: "#demo", data() { return ...

It is not possible to submit two forms at once with only one button click without relying on JQuery

I need to figure out a way to submit two forms using a single button in next.js without relying on document.getElementById. The approach I've taken involves having two form tags and then capturing their data in two separate objects. My goal is to hav ...