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

What is the best way to route a localpath to a different page including parameters in Nuxt Js?

Hello, I am facing an issue where I need to pass parameters in the URL to another page in NuxtJs props: { idPending: { type: Number, required: true } }, methods: { fetchpage() { const orderId = this.idPending; this.$rou ...

Is it possible for Penthouse to retrieve critical CSS while using javascript?

I am currently utilizing the laravel-mix-criticalcss npm package to extract the critical CSS of my website. This package leverages Penthouse under the hood, and you can configure Penthouse settings in your webpack.mix.js within the critical options. The ...

Is it possible to determine if the clipboard is accessible in Firefox?

In my upcoming JavaScript project, I am looking to determine the accessibility of the clipboard. Particularly in Firefox where specific permissions need to be granted for each site in order to use certain functions like execCommand with cut, copy or past ...

Utilize Vue to access and read a file stored in the current directory

I am attempting to retrieve data from a text file that is located in the same directory as my .vue file. Unfortunately, I am encountering an issue where the content of the text file is not being displayed in both Chrome and Firefox. Instead, I am seeing th ...

Using jQuery's AJAX function to send a POST request and extracting data from the response

Below is the jQuery AJAX call that I am using: $.ajax({ method: "POST", url: "/Agenda/Template", dataType: 'json', data: { "templateId": templateSelect.options[templateSelect.selectedIndex].value }, c ...

Navigate to the editing page with Thymeleaf in the spring framework, where the model attribute is passed

My goal is to redirect the request to the edit page if the server response status is failed. The updated code below provides more clarity with changed variable names and IDs for security reasons. Controller: @Controller @RequestMapping("abc") public clas ...

Move the internal array pointer forward to the next record in order to apply the insertAfter function within the jquery code

As a new jQuery user, I'm attempting to develop a jQuery function using data provided by PHP. My goal is to arrange DIV elements in order of their values using insertAfter method. However, I seem to be encountering some difficulty in advancing the poi ...

Adding the location of the onClick event to the hook - a step-by-step guide

Here is the code I am working with: import { MapContainer, TileLayer } from "react-leaflet"; import React, { useState } from 'react'; export default function App() { const [positionLat, setPositionLat] = useState(null); ...

Why does the browser keep converting my single quotation marks to double, causing issues with my JSON in the data attribute?

This task should be straightforward, but I seem to be facing a roadblock. I am trying to insert some JSON data into an input's data attribute, but the quotes in the first key are causing issues by prematurely closing the attribute. Here is the code ...

Obtaining undefined values for req and resolvedUrl in GetServerSideProps function

In my project, I am currently using next.js version ""next": "^12.1.4"" and node version ""@types/node": "^14.14.6". I have created a function called getServerSideProps with parameters req and resolvedUrl. When the ...

Changing the CSS class of the Bootstrap datetime picker when selecting the year

Is there a way to change the CSS style of the Bootstrap datetime picker control so that when selecting years, the color changes from blue to red? I attempted to do this with the following code: .selectYear { background-color:red!important; } However ...

Struggling to retrieve data with arrow function in Vue

I'm currently learning Vue and facing an issue with fetching data from an API to my component. I have a service class that successfully retrieves data from the API, as the API itself is working fine. Here's the code snippet: import IReview from & ...

When using Angular 2, the array.splice() function is causing the elements to be removed from the

I am currently working with an HTML table that has default checked rows. <table> <tr> <th></th> <th>Id</th> <th>Name</th> <th>Initial</th> </tr> ...

Incorporating Bootstrap Navbar into a create-react-app project

I recently created a new project using create-react-app. To incorporate Bootstrap into my project, I followed these steps: npm install --save bootstrap@3 Next, I imported Bootstrap in my root file index.js: import 'bootstrap/dist/css/bootstrap.css& ...

Troubleshooting a problem with selecting options in Jquery

Looking for assistance with a jquery script. I have a select dropdown that fetches a list of options via Ajax. When a user clicks on an option, if a certain variable equals 1, an HTML div is added. If the variable changes to another value, the HTML div dis ...

Answer processing for the reminder dialog is underway

When I send a proactive message to a user, I want to initiate a 'reminder dialog'. The dialog is displayed, but when processing the response it goes back to the main dialog. This is how I currently set up my bot: const conversationState = new C ...

What is a reliable method for consistently updating backend C# with user-side JS data whenever it is altered?

I'm working on a front end JS application that includes visual sliders. I need to send the updated slider information to the C# backend (ASP.NET) whenever a user makes changes. After some research, it seems like AJAX is the most efficient way to achie ...

Is it possible to refresh a table that is currently displayed in a model popup?

My code to reload a table or div inside a model popup continuously is not working as expected. Can you help me with this issue? I attempted to utilize ajax for this purpose but unfortunately, the code below is not updating chats (I am working on a chat ta ...

Transforming data from an HTML table into a MySQL database

Is there a way to transfer data from an HTML table created with JavaScript to a SQL database? I have been experimenting with the addRow(tableID) function but it doesn't seem to work. Any suggestions on how to solve this issue? Below is the code snipp ...

Methods for retrieving and persisting the data from a particular row within a table using JavaScript or jQuery

Is there a way to store the selected row values of a table in an array of arrays using JavaScript / jQuery? Check out this JSFiddle I believe that we should listen for the event when the 'Show selected' button is clicked. For instance, in Java ...