I'm currently working on my first CRUD web app using Vue 2 + Vuetify, but I've hit a roadblock while trying to add validation to a form. Specifically, I need to ensure that no item with the same title already exists in the database.
You can view the code sample with a fake API, or see below for the code snippet using the real API.
Here is the HTML portion:
<v-form ref="form" lazy-validation>
<v-text-field
v-model="editedItem.title"
:rules="[rules.required, checkDuplicate]"
label="Title"
></v-text-field>
</v-form>
The Method part:
data() {
return {
editedItem: {
title: '',
},
rules: {
required: value => !!value || 'Required.',
},
}
},
methods: {
checkDuplicate(val){
let params = {};
params["title"] = val;
if (val){ //If null, don't call the API
InventoryDataService.findExactTitle(params)
.then((response) => {
if(response.data != ""){ // Same title are found
if (val == response.data.title) { // Can be discarded, but just to make it same as code sample
return `Inventory titled ${val} already exists`;
}
}
else{ // No same title found
return true;
}
})
.catch((e) => {
console.log(e);
});
}
else{ // Text field is empty
return true;
}
},
}
The actual API will return either no data if there isn't a duplicate title, or exactly one record if the same title already exists. The logic works when checking outside of the axios.then block (uncomment this part in the code sample to test it), comparing to "test" and validating correctly. However, when this comparison is within the .then block, it doesn't work at all! (both using "test" and response.data.title)
I have attempted to store the response in a variable outside of axios.then for external comparison, but due to the asynchronous nature, it seems impossible (I still struggle to understand this concept?). I've experimented with async-await and consulted various resources on Stack Overflow, yet none have resolved the issue.
Is there any workaround to address this challenge? I am open to modifying my approach as long as the desired feature is achieved. Apologies if the code appears messy, as I followed a tutorial and made adjustments along the way. Please let me know if you require additional information. Thank you for your assistance!