I have recently developed a Vue3 shopping cart with an "Add One" button feature. When the user clicks this button, it updates an input field of type "number" and sends a request to update the database using Axios along with Laravel's createOrUpdate method. Additionally, I have set up the Axios request to be triggered whenever there is a change in the input field content. This means that users can either manually enter the quantity or simply click the plus button to increment the value by one and automatically update the database through Axios.
Below is the current code snippet:
<input
name="qtyInput"
type="number"
v-model="qtyInput"
/>
<button @click="addOneItem" >ADD ONE TO CART</button>
To handle the rapid clicking issue, I have implemented a watcher function which detects changes in the 'qty' constant and triggers the addProductToCart() function responsible for sending the Axios request.
<script>
import axios from "axios";
export default {
setup() {
const qty = ref(0);
const qtyInput = ref(0);
let cartitem = ref({
product_id: 1,
qty: qty,
});
const addOneItem = () => {
qty.value++;
qty.value = qtyInput.value;
};
const addProductToCart = () => {
axios
.post("/api/update-cart/", cartitem.value)
.then((response) => {
console.log('Success! Data saved in the database.');
})
.catch(function (error) {
return error;
});
}
};
watch(qty, async (newQty, oldQty) => {
addProductToCart();
});
return {
qtyInput,
qty,
addOneItem,
cartitem
};
},
};
</script>
Despite the functionality working well in most scenarios, I encountered an issue where frequent clicks on the "Add One" button resulted in an "Axios Error - Too Many Requests". Furthermore, I find the system inefficient as each click generates an Axios request towards creating/updating entries in the Laravel backend. **How can I enhance the system design to prevent excessive requests while enabling the user to click multiple times without causing errors?**