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

Struggling with retrieving empty parameters, queries, and body from an Axios API call for the past three days. It's a learning experience as I am new to the MERN stack

There seems to be an issue where only empty JSON like {} is coming as output. I am looking for a way to access the parameters sent from the routes in this scenario. On the Frontend: let api = axios.create({ baseURL: "http://localhost:5000/validateSignI ...

Searching for text within a PDF document using the Internet Explorer version 9 browser by

When a link is clicked in our application, it opens a new window with a secure PDF file. We are looking to validate this using Selenium in Ruby. However, we encountered an issue in IE9 where there is no HTML/DOM element for validation. We were able to suc ...

Out-of-sync movement in animated characters

Looking for some assistance with my page coding. I have a scenario where two stars are moving around a button, simulating an animation by incrementing the CSS properties top and left. Initially, everything appears fine and they move synchronously. However, ...

How do I navigate to the homepage in React?

I am facing an issue with my routes. When I try to access a specific URL like http://localhost:3000/examp1, I want to redirect back to the HomePage. However, whenever I type in something like http://localhost:3000/***, I reach the page but nothing is dis ...

How can you specify the environment in Google Tag Manager?

I have integrated google tag manager and google analytics using the vue-gtm plugin found at vue-gtm Within google tag manager, I have set up 3 environments under the same container. In a user-defined variable called GA from environment, I have created a ...

JavaScript: Organize an array of objects into separate sections based on a specific field

Presented below is a set of data: const dataSet = [ { id: '1', name: 'River', address: 'Terminal A', type: 'OTHER', code: null, targetArrivalStep: 30, disabled: true, }, { id: &a ...

Show a specific div using jQuery fadeIn() when the user reaches the top of an HTML section

The code below has a specific purpose: 1) Determine the current scroll position. 2) Locate the parent article and determine its offsetTop for each .popup_next which represents a section on the site. 3) Calculate an offset value by adding 30px to the off ...

Insert a design layout into a text entry box

Currently developing an application with AngularJS and seeking a solution for adding a "template" to an HTML input field similar to a placeholder. Specifically, I have a date-field requiring user input in the format of dd/MM/yyyy or through a datepicker se ...

Quasar Vue project not recognizing onBeforeUpdate and onUpdate triggers

I have a basic application with three key components: counter button that increments the counter onBeforeUpdate and onUpdate hooks CRUCIAL NOTE: I attempted to replicate this issue on a pure Vue Vite project and encountered no problems there. It seems to ...

The upload method in flowjs is not defined

I am a novice when it comes to flow.js and am currently using the ng-flow implementation. I have a specific task in mind, but I'm unsure if it's feasible or not, and if it is possible, how to achieve it. I've created a factory that captures ...

Angular 2: Executing a function after ngFor has completed

Within Angular 1, I crafted a personalized directive called "repeater-ready" to pair with ng-repeat for triggering a callback method upon completion of an iteration: if ($scope.$last === true) { $timeout(() => { $scope.$parent.$parent.$ ...

Guidelines for incorporating a router into the title of a Vuetify.js toolbar

I am currently utilizing vuetify.js in my project and I encountered an issue. I wanted the application title to link to the top menu, but when navigating to /route shop and /discount, the HogeHoge button's state changed unexpectedly. Is there a soluti ...

Canvas - Occasionally, using lineTo() can result in crisp edges in the drawing

I've created a simple Canvas drawing app. However, I've noticed that occasionally the lineTo() command generates a line with fewer coordinates, resulting in many edges: I'm currently using the latest version of Firefox - could this issue be ...

Rotate object within HTML table

I have a simple data structure as shown below: [ { "ClientId": 512, "ProductId": 7779, "Date": "2019-01-01", "Quantity": 20.5, "Value": 10.5 }, { "ClientId": 512, "ProductId": ...

Combining two input text strings

A React component I'm working on takes the user's first and last name to create unique usernames for them. class App extends Component { render() { return ( <div className="App"> First name:<br/> <input ...

Are there any plugins available that can create a Ken Burns effect using JQuery?

All I need is a straightforward plugin, not one for creating slideshows. In this case, I only have 1 div and 1 image. The goal is to have the image animate within the div, shifting left/right or up/down without any white space visible. The size of the ima ...

React doesn't properly display JSON data

I am facing an issue with the code below that is supposed to display data from a JSON file. Instead of showing the desired data, it only displays the h1 with curly braces. Here is the faulty code: import prod from "../../data/produtos.json"; exp ...

Ways to access a field value in SAPUI5

As I delve into OPENUI5/SAPUI5, I'm faced with the task of accessing data for the controls I've implemented. For instance: <Label text="Amount" /> <Input id="inputAmount" value="{Amount}" /> <Text id="lblCurrency" text="USD" > ...

Optimal method for centrally aligning a v-card both horizontally and vertically using Vuetify

I'm currently working on the login page for my website and I'm having trouble centering my v-card both horizontally and vertically. The code I have right now is as follows: <template> <v-layout align-center justify-center column fill ...

Sketch on canvas using vue framework

I am trying to modify a selection tool using rectangles that was created with JS and HTML in Vue.js. Here is the original version: https://codepen.io/sebastiancz/pen/mdJVJRw initDraw(document.getElementById('canvas')); function initDraw(canvas) ...