I encountered an issue with my validator function that checks if a username is already registered in the database. The problem was that the request was being sent to the server after every single character input, which was far too frequent. To remedy this, I attempted to debounce the process of setting the username variable value. However, I kept running into this error:
Uncaught TypeError: Cannot read property 'value' of undefined
at a.NHnr.q.methods.debounceUsername.H.a.debounce.leading
Vue script:
import uniqueUsername from '../validation/uniqueUsername'
import _ from 'lodash'
export default {
name: "signUpPage",
data() {
return {
credentials: {
username: ''
}
}
},
methods: {
debounceUsername:
_.debounce(function (e) {
this.credentials.username = e.target.value;
}, 200, {leading: false, trailing: true})
},
validations: {
credentials: {
username: {
uniqueUsername: uniqueUsername
}
}
}
}
Html:
<b-field :label="msg('usernameLabel')"
:class="{ 'form-group--error': $v.credentials.username.$error }">
<b-input size="is-large" type="text" class="form__input"
icon="account" name="username" v-on:input="debounceUsername" autofocus="">
</b-input>
</b-field>
//b-field and b-input are from buefy library
Custom validator (uniqueUsername.js):
import axios from 'axios'
export default value => {
if (value.trim().length === 0) return true;
let usernameUnique;
return new Promise(async function (resolve) {
await axios('/isUsernameUnique', {
method: "post",
data: value,
headers: {'Content-type': 'text/plain'}
}).then((response) => usernameUnique = response.data);
if (usernameUnique) resolve('username is unique');
});
};