When the user clicks the submit button of my form, handleSubmit
is called. So, I want to properly call the e.preventDefault() inside my ajax call which is not possible due to the async nature of ajax. How can I fix this?
class FormRegister extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
email: '',
}
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
// some code here
// Check for username or email already exists
$.ajax({
type: 'POST',
url: '/api/checkEmailUsername',
data: {
username: this.state.username,
email: this.state.email
}
}).then(function(incomingJSON) {
console.log('incomingJSON:', incomingJSON);
if (incomingJSON.error) {
e.preventDefault();
}
}
});
}