1👍
✅
Observation/Suggestion : Before making an API call to submit the form data, You should validate the form data as per the requirement and if validation passed then only make an API call.
Now as per the answer of I’d like to change the loading property to true as the request is processing
On top of the above suggestion, you can make this.loading = true
on submit and then on API response you can make it this.loading = false
.
submit() {
this.loading = true;
axios
.post("/api/login", this.fields)
.then((res) => {
this.loading = false;
if (res.status == 201) {
this.$router.push("/dashboard");
}
})
.catch((error) => {
this.loading = false;
if (error.response.status == 422) {
this.errors = error.response.data.errors;
}
});
}
3👍
You can set a timer before calling the api which then toggles and the loading goes away.
<script>
export default {
data() {
return {
fields: {},
errors: {},
loading: false
};
},
methods: {
submit() {
this.loading = true
setTimeout(function(){
this.loading = false
}, 2000);
axios
.post("/api/login", this.fields)
.then((res) => {
if (res.status == 201) {
this.$router.push("/dashboard");
}
})
.catch((error) => {
if (error.response.status == 422) {
this.errors = error.response.data.errors;
}
});
},
},
};
</script>
1👍
Use async/await as bellow. This solution is perfect when you handle errors on backend.
methods: {
async submit() {
this.loading = true;
try{
const res = await axios
.post("/api/login", this.fields);
if (res.status == 201) {
this.$router.push("/dashboard");
}
}catch(error){
if (error.response.status == 422) {
this.errors = error.response.data.errors;
}
};
this.loading = false;
},
},
0👍
like this:
<script>
export default {
data() {
return {
fields: {},
errors: {},
loading: false
};
},
methods: {
submit() {
this.loading = true
axios
.post("/api/login", this.fields)
.then((res) => {
this.loading = false
if (res.status == 201) {
this.$router.push("/dashboard");
}
})
.catch((error) => {
if (error.response.status == 422) {
this.errors = error.response.data.errors;
}
});
},
},
};
Source:stackexchange.com