Enhancing User Experience: Creating a Vue Button Component for Adding Items to Cart with the Power of Axios and Laravel Backend Integration

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?**

Answer №1

If you're looking for a solution to your query, I recommend utilizing either useDebounceFn or watchThrottled from the vueuse library. For more details, you can check out the documentation here.

Another alternative is to store the cart data in localStorage. This can be achieved by leveraging pinia along with pinia-plugin-persistedstate.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I can't believe this ReactJs project generated this code automatically

What does this automatically generated code do in my ReactJs app and what are the advantages of including it? <div class="nsc-panel nsc-panel-compact nsc-hide"> <div class="nsc-panel-move"></div> <div class=" ...

Error: An attempt was made to wrap a property called "find" as a function, but it is

I am currently implementing a test-driven development approach to run my tests. I have successfully run the same test on another application by copying and pasting it, but I encountered an error in this particular test: TypeError: Attempted to wrap unde ...

using variables as identifiers in nested JSON objects

Within my code, there is a JSON object named arrayToSubmit. Below is the provided snippet: location = "Johannesburg, South Africa"; type = "bench"; qty = 1; assetNumber = 15; arrayToSubmit = { location : { type : { 'qty' ...

Device sending incorrect JSON format

A JSON response from a device is as follows: { "Order": ""3"", "ID": ""SHEET"", "Name": ""Time Sheet"", "ConID": ""!s?d2SzxcSDW1cf$*@4812sC#"" } The property values in the JSON are enclosed in double quotes, causing them to be incorrect. Is ...

Having trouble getting the .replace() Javascript function to work on mobile devices?

I have a code snippet for implementing Google Analytics. Here it is: $(function () { $('.plan-choose-btn a').bind('click', function(e) { //ga load image <% String myaccGAEventUrl = trackGoogleAnalyticsEvent(requ ...

Managing JSON Forms using jQuery on Google's App Engine

Having difficulty getting jQuery to function properly on GAE in python 2.7. The main issue is that jQuery is unable to retrieve the json data sent by the server. A basic comment form with no special features: <form action="/postcomment/" method="post" ...

Creating dynamic stylesheets with the help of PHP and JavaScript

Generating tooltips based on a dynamically changing background image in CSS is my goal. Within my file named my_css.php, I have implemented the following code: <?php header('content-type: text/css'); $i = $_GET['index']; ...

Managing uncaught exceptions in node.js

While working on my project, I encountered an issue with catching exceptions when opening a connection using mongoose.createConnection. Here's the code snippet causing the problem: var createdDb = mongoose.createConnection(connectionString); createdD ...

Passing events from Vue to child components

Looking for a way to make clicking on the outer pill element have the same effect as clicking on the checkbox itself? Check out this HTML code that renders these little boxes: <div class="token-checkboxes"> <span class="checkbox-span" v-for=" ...

Having trouble with Cordova, Angular, and PushPlugin? Your callback isn't firing

While searching for solutions, I noticed various similar items but none were quite the same context as mine (Angular specifically, not using Ionic). My Cordova version is 5.0.0 (confirmed through 'cordova --version' in CMD showing 5.0.0, and in t ...

What could be causing the Ioncol not triggering the Onclick event?

I am facing an issue where my onclick event is not working on an ion-col. The error message says that the method I call "is not defined at html element.onclick". Here is a snippet of my code: <ion-row style="width:100%; height:6%; border: 1px solid # ...

Discover distinct and recurring elements

Having two sets of JSON data: vm.userListData = [{ "listId": 1, "permission": "READ" }, { "listId": 2, "permission": "WRITE" }, { "listId": 2, "permission": "READ" }, { "listId": 3, ...

Automatically refreshing controller functionality in CodeIgniter

Greetings everyone, I'm looking for a way to automatically refresh a controller function every 5 seconds. Currently, I am using header('Refresh: 10.2'); within the controller function like this: public function delete() { heade ...

Add a class individually for each element when the mouse enters the event

How can I apply the (.fill) class to each child element when hovering over them individually? I tried writing this code in TypeScript and added a mouseenter event, but upon opening the file, the .fill class is already applied to all elements. Why is this ...

Is there a way for ASP.NET MVC to automatically notify when a record is edited or updated?

Having recently used the NotifyIcon class in a windows application, I found it to be quite useful. As someone who primarily works as a web developer, I am curious if there is something similar available for websites. The website that I am working on inclu ...

What is the most efficient way to retrieve key pair values of separate elements in an array with just one API request?

The API I am working with returns an array of elements, each containing multiple key-value pairs. An example of a similar API response can be seen here: , where an array of poems is returned. [ { "title": "...." "content": "..." "url" : "..." } ...

What steps can be taken to access the body prior to uploading a file using multer?

In my current project, the administrators are able to upload MP3 files and input parameters such as the song name. I have chosen to utilize the multer middleware for managing multipart/form-data. The issue I am facing is that req.body.gender always retur ...

"Trouble Encountered with the dragAndDrop Function in WebdriverIO Version

I've been experimenting with different methods like dragAndDrop and performAction, but unfortunately, none of them seem to be working for the Vue.Draggable web app (for example: vuedraggable: Two Lists). Can anyone offer a solution if possible? Here ...

Storing a collection of images simultaneously in Firebase Storage and saving their URLs in a Firestore document using Firebase v9

I am currently working on a form that requires users to input data in order to generate a detailed city document. Additionally, users must upload multiple photos of the city as part of this process. Once the form is submitted, a new city document is create ...

Convert the button element to an image

Can someone please explain how to dynamically change a button element into an image using javascript when it is clicked? For instance, changing a "Submit" button into an image of a check mark. ...