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

How can you ensure that the object passed to a component becomes reactive in Vue?

Unique Codepen Demo In my component, I am working with a location object passed as a props. Specifically, the argument I used is locations[index], which represents a selected item from an array of locations. The issue I'm facing is that the componen ...

Authenticate users using Laravel's default authentication system, then serve the Vuejs single page application only to logged

Currently working on a Single Page Application using the default Laravel scaffolding: // Setting up basic scaffolding... php artisan ui vue // Implementing login / registration features... php artisan ui vue --auth These commands provide a solid foundati ...

The Google Maps geocoding service fails to provide accurate location information

I am currently attempting to utilize the Google Maps Geocoding API within my JavaScript code. Below is the snippet I have written: var geocoder = new google.maps.Geocoder(); function geocodeAddress() { var address = document.getElementById("address").v ...

Looking to Move the Image Up?

I've been experimenting with creating a grid layout where the bottom image will move up until it is 10px away from the image directly above it. However, no matter what I attempt, the spacing seems to be based on the tallest image rather than the one a ...

Implementing jsGrid: Appending a row with JSON information

Is there a way to dynamically insert a row in jsGrid? I found some helpful code examples at https://github.com/tabalinas/jsgrid/blob/master/demos/db.js ...

Docz: Utilizing Typescript definitions for props rendering beyond just interfaces

We are currently using Docz to document our type definitions. While it works well for interfaces, we've run into an issue where rendering anything other than interfaces as props in Docz components doesn't seem to display properly. I'm seeki ...

Displaying a collection of items using Rails, implementing form_for and integrating Ajax functionality

Looking to display a list of "Interests" for users to "follow" by clicking on a button linked to the Interest's image. Once the follow button is clicked, the Interest and its image should be removed from the list. Attempting to use a hide function in ...

Vue: passing parameters between application and component through computed properties

I apologize for the basic question as I am new to Vue and struggling to find the right terminology to search for answers. I recently started learning Vue through this course (). The lesson involves a critical app-level data parameter named cart, which is a ...

Unable to connect beyond the local network using Socket.io

server.js import { Server } from "socket.io"; const io = new Server(8000); io.on("connect", (socket) => { console.log(`connect ${socket.id}`); socket.on("ping", (cb) => { console.log("ping"); ...

The console is displaying a null value outside of the block, however, the correct value is returned when

I am having an issue where the first console.log() is not returning the correct value, but the second one is. Can anyone provide assistance with this problem? angular.module('resultsApp', ['ngCookies']) .config(['$qProvider&a ...

Is it possible to use a webcam to scan a QR code directly into a webpage?

Is it possible to enable users to input data on a webpage using QR code scanning? I'm unsure if there is a tool that can be integrated into the page or paired with a library to make this happen, or if I need to consider an external solution beyond th ...

Populate several input boxes with data derived from a single input field

I am facing an issue with three textboxes in my project. When I type something in the first textbox, the value is sent to state.jsp and displayed using out.println(firsttextboxvalue); on the response ID of the second textbox. However, I want to populate th ...

Enhance the editing capabilities of the Json data form

https://i.stack.imgur.com/YZIjb.png My goal is to enhance a form for editing json data by moving beyond the typical <textarea /> tag and making it more user-friendly. Are there any tools available that can help improve the form's usability? Add ...

Output JSON data from PHP for use in Javascript

Is there a way to effectively convert JSON data from PHP/Laravel into JSON for JavaScript? I have the JSON string from PHP, but it is only rendering as a string. How can I convert it to a JSON object in JavaScript? Take a look at my code below. $('#e ...

Unexpected resizing of a div due to Vue animation

I'm currently working on a quiz and I'm trying to incorporate some animation effects when users navigate between questions. I've been experimenting with a fade in and out effect, but there seems to be a glitch. Whenever I click the button, t ...

VueJS: Unable to access the 'name' property as it is undefined"

I'm at a loss trying to figure out a solution for this issue. My current task involves editing a pub schedule using an edit form: pubs/UpdateProfile.vue <template> <confirm title="Edit Pub" ok="Save pub" :show="show" v-on:save="sa ...

Inquiry into the use of Jquery.ajax()

Hey there, I'm curious about using Jquery Ajax to retrieve a numeric value from a website. Any suggestions on where I should begin? Any advice would be greatly appreciated. Thanks in advance! Best regards, SWIFT ...

Utilizing an array in a PHP URL and incorporating it into JavaScript operations

In this PHP file, I am working on validating only numeric input for text-boxes with the ids "Mobile" and "Home": $elementids = array("Mobile","Home"); $serialized = rawurlencode(serialize($elementids)); $testvar='validate-nums.php?elementids='. ...

Error: Vue.js is unable to find the reference for "_vm.KisanData" and throws a TypeError

I need assistance in fixing an error that I am encountering. The issue arises in this method where I am using KisanData, but I am unable to resolve it. const API_URL = "http://localhost:3000/User"; export default { name: "home", info(){ ...

sending information back to the controller with get method (ajax, javascript)

I'm currently facing a challenge where I have an event listener waiting for a button to be pressed. Once the button is pressed, the controller method 'update' is called which then triggers the view method 'input' to fetch data from ...