Step-by-step guide on integrating async and await functionality into Vuetify rules using an ajax call

I'm currently using Vuetify form validation to validate an input field, and I'm exploring the possibility of making an ajax get call await so that I can utilize the result in a rule. However, my attempts at this approach have not been successful!

export default {
  data() {
    return {
      rules: {
        isLocationNew: value => {

          if (value == '' || value == null || value.length <= 1) {
            this.validLocation = false;
            return 'Invalid length.';
          }

          this.validLocation = true;

          var hasName = this.checkDuplicateLocation(value);
          if (hasName) {
            return 'Location name already exists.';
          } else {
            return true;
          }
        }
      },


      // Defined method below
      methods: {
        async checkDuplicateLocation(text) {
          if (text == '' || text == null || text.length <= 1) {
            return false;
          }

          let response = await axios.get('/api/Locations/HasLocationName', {
            params: {
              text: text,
              jobsiteId: this.jobsiteId
            }
          });
          
          return response.data;
        }
      }

Answer №1

I stumbled upon a more effective solution when faced with the task of verifying an email address in the database. Instead, I utilized 'error-messages'

in a manner similar to this

@input="newLocationNameSearch($event)" :error-messages="newLocationErrorMessages"

This approach involves validating each character entered through 'newLocationNameSearch()' and managing 'newLocationErrorMessages' to provide feedback to the user!

Answer №2

checkLocationName is a function that returns a promise as it is an async function. So, when you use the function like this:

var hasName = this.checkLocationName(value);

hasName will store a promise object, which always evaluates to truthy in JavaScript.

To handle the promise correctly, the function should look something like this:

    isNewLocationValid: async value => {

      if (value == '' || value == null || value.length <= 1) {
        this.validLocation = false;
        return 'Invalid length.';
      }

      this.validLocation = true;

      var hasName = await this.checkLocationName(value);
      if (hasName) {
        return 'Location name already exists.';
      } else {
        return true;
      }
    }

Don't forget that you need to await the call to isNewLocationValid wherever it is being used.

Additionally, the checkLocationName method does not return any value when awaited as shown below:

      await axios.get('/api/Locations/HasLocationName', {
        params: {
          text: text,
          jobsiteId: this.jobsiteId
        }
      }).then(response => {
        return response.data;
      }).catch(function(error) {
        console.log(error)
      })

The problem here is with the return statement inside the .then() callback. As a result, checkLocationName returns undefined, which is falsy.

Fortunately, using async/await eliminates the need for .then callbacks. You can rewrite the code like this:

try {
     var response = await axios.get('/api/Locations/HasLocationName', {
        params: {
          text: text,
          jobsiteId: this.jobsiteId
        }
      });

      return response.data;

} catch (error) {
    console.log(error)
}

Answer №3

functions: {
  getUserData: async function() {
      const feedback = await fetch(
            "https://jsonplaceholder.typicode.com/users"
      );
      this.userList = await feedback.json();
}

This is an illustration of how to utilize it.

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

Acquiring JSON data within a JavaScript function using PHP

Requesting assistance on reading a JSON value using the code below, to retrieve data based on the $movieID. <script> function bookBTN(x) { <?php $url = 'http://movie.com/movieOne?seatNum=' . x; $jsonURL = file_get_ ...

Tips for Sending Form Data to the Controller in MVC Using Ajax, No Model Needed

I am looking to send Property name and values from a form to an Mvc web api Controller without using model Property. This is because I want to use the same Ajax call method for different forms as well. While I am able to post the values using this Ajax Me ...

The condition is not established by the Firestore where clause

I'm working on a function that includes two where clauses. My objective is to verify the existence of a document based on the presence of two specific IDs. However, when I execute the function, it retrieves all the records in the collection instead. C ...

Maintaining scope integrity in an Angular application with components, including a dialog that utilizes a custom directive

I'm struggling with passing scope to a template rendered from a directive. It seems like it should be simple, but I can't seem to get it to work properly. Here is a simplified version of my HTML: <div ng-app="myApp"> <md-content> ...

Issues with retrieving information between AJAX and PHP (and vice versa)

I have a script that sends the value of a text input from an HTML form to emailform.php. This PHP file then adds the data to a .txt file. The issue I'm facing is setting the value of $email in the PHP file to match that of the HTML input field. Curren ...

Attempting to iterate over a JSON object and display its contents using HTML

I have been attempting to iterate through this JSON data and display it in an accordion format similar to the one shown here: but unfortunately, my implementation is not functioning correctly. Here is what I currently have: HTML: <div class="a ...

Is there a way to automatically determine the text direction based on the language in the input text?

When posting in Google Plus (and other platforms), I noticed that when I type in Persian, which is a right-to-left language, the text direction changes automatically to rtl and text-alignment:right. However, when I switch to English, the direction switches ...

Adjust the cursor in a contenteditable division on Chrome or Webkit

Is there a way to set the caret position in a contenteditable div layer? After trying different methods and doing some research online, I finally found a solution that works in firefox: function set(element,position){ element.focus(); var range= w ...

I wish to transfer over the identical ajax attribute

java persistence api select id="retrieveMultipleRecords" parameterType="map" resultMap="elementResultMap" ${sql} /select mongodb select * from (select * from ELEMENT where I_NO=1) T1 inner join (select * from ELEMENT where I_NO ...

The installation of robotjs via npm failed due to issues encountered while trying to build the binaries

After attempting to execute the command "npm install robotjs -g," an error is thrown back at me. [email protected] install C:\Users\Ehsan\AppData\Roaming\npm\node_modules\robotjs prebuild-install || node-gyp reb ...

Javascript is failing to execute promises in sequence

Currently, I am facing an issue with the execution of the code below using promises. The problem lies in the fact that the promise is not executing sequentially; it does not wait for the first block to finish before moving on to the next block. Here is th ...

Menus that mimic the style of Google Translate's select options

I'm looking to design an HTML select menu using CSS in a similar fashion to Google Translate's style on Google Translate. I've searched for tutorials online, but they all involve jQuery. Is there a way to achieve something similar using only ...

The Powerful Duo: AJAX and the Model-View-Controller Framework

Can anyone redirect me to a similar question, if one exists? I've searched but haven't found anything specific. I'm sure my issue is quite common... I am working on a page that contains 5-6 divs which can be loaded individually through Ajax ...

Issue encountered while attempting to retrieve a response from CodeIgniter through Ajax code

I need to send a request to CodeIgniter in order to receive a response from my database: $(document).ready(function(){ $('.confirm_send').on('click',function(){ var base = '<?php echo base_url(); ?>'; var confirm_sen ...

Tips on keeping Bootstrap Modals out of your browsing history

Imagine this scenario A visitor lands on Page A, clicks through to Page B, and then engages with a link that triggers a modal (code provided below) <a href="mycontent.html" data-target="#modal_xl" data-toggle="modal" data-backdrop="static">Click me ...

Tips for managing the onblur event using selenium automation framework

I want to trigger an onblur event when I click away using JavaScript. I tried the following code: ((JavascriptExecutor)getDriverProvider().executeScript("document.getElementByXpath('xpath here').onblur();"); However, it doesn't seem to wo ...

AJAX-enhanced Pagination in CFWheels

I have scoured the depths of the internet, high and low, but I am unable to find a solution to this problem. Currently, I am utilizing the ColdFusion CFWheels Framework for database querying through AJAX as shown below: var id = $("#ship-id").val(); $.a ...

Tips for managing nested arrays using a v-for loop

Imagine I have a dynamic dropdown menu that needs to be filled with items based on the selection made in the previous dropdown. For example, consider a scenario where vehicle data is structured like this in a file named vehicleDetails.json: { "1": { ...

Issue persists with Angular 2 *ngFor functionality even after successfully importing CommonModule

After creating a feature module using the CLI, I imported the common module as shown below: import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HomeComponent } from './home/home.compo ...

Implementing Cors in Laravel 5.6 using Passport for authentication and Vue.js with Axios for making API calls

After extensive research on solving my CORS problem, I came across this package that promised to resolve everything. However, despite my attempts to implement it, I have yet to find a solution. The error I'm encountering is: Failed to load https://b ...