Is there a way to lower the cost with the same value that was used to raise it?

My goal is to adjust the price when the user clicks on the minus icon. However, I want the new price after decreasing to revert back to the initial price.

quantityHandler: function (action, product) {
      // Increase or decrease quantity of product
      try {
        const newItems = [...this.products]; // clone the array
        let idx = newItems.indexOf(product);
        let currentQty = newItems[idx].productQuantity;
        let price = newItems[idx].unitPrice;

        if (action == "more") {
          newItems[idx].productQuantity = currentQty + 1;
          newItems[idx].unitPrice = price + price;
        } else if (action == "less") {
          newItems[idx].productQuantity = currentQty > 1 ? currentQty - 1 : 1;
          // Decrease the current price using the original price
        }

        this.products = newItems; // set new state
        console.log(this.products);
      } catch (error) {
        alert(error);
      }
    },

Answer №1

updateQuantity: function (action, item) {
      // Adjust the quantity of a specific item
      try {
        const updatedItems = [...this.items]; // create a copy of the array
        let index = updatedItems.findIndex((element) => { // find item by unique identifier
         return element.id === item.id
        })
        let currentQty = updatedItems[index].quantity;
        let price = updatedItems[index].price;
        let perItemPrice = price / currentQty;  // calculate per item price
        if (action == "increase") {
          updatedItems[index].price += perItemPrice;
          updatedItems[index].quantity = currentQty + 1;
        } else if (action == "decrease") {
          if(currentQty > 1) {
           updatedItems[index].price -= perItemPrice;
           updatedItems[index].quantity = currentQty > 1 ? currentQty - 1 : 1;
          }
        }

        this.items = updatedItems; // update state with new values
        console.log(this.items);
      } catch (error) {
        alert(error);
      }
    },

Calculate the price per item and adjust accordingly when increasing or decreasing quantity

Answer №2

Incorporating negative numbers into your calculations is possible. Here's an example:

newTotal = currentQuantity * itemPrice
if (action === 'less') {
    newTotal *= -1;
}
// By adding a negative number, the total will decrease

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

Navigating through object arrays using a loop

I have multiple arrays within an object that I would like to iterate through using numeric values. This is necessary in order to assign them to different slots in an accordion loop. The JSON file containing the data looks similar to this (Pokemon used as a ...

What is the best way to adjust the scroll speed within a specific element using React?

Hey there, I'm currently working on adjusting the scroll animation of a div (MUI Container) to make it smoother and slower. I've spent some time searching online for a solution but haven't found anything helpful so far... By the way, I' ...

When the button is clicked, send data using 'POST' method to the php file and fetch

<script> $(document).ready(function(){ $("#vE_rebtn").click(function{ var reverifyEmail = '<?php echo $_SESSION["verifyEmIPv"]; ?>'; $('#rE_rebtn').hide(); $('#re_ ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...

Creating a table in React.js by mapping array data from console.log output

I am working with an API that returns an array of results when called using axios.get(). I am trying to map this array into a table in a React JS application. Here is the code for fetching data from the API: const [data, getData] = useState([]) u ...

Is it possible to send properties to a React Component using a regular function?

import C from './C.js'; const Solution = () => { async function fetchData() { await axios .get(`http://localhost:2000/?url=${link}`) .then((response) => { <C data={response.data} / ...

Creating Vue Components indirectly through programming

My goal is to dynamically add components to a page in my Vue Single file Component by receiving component information via JSON. While this process works smoothly if the components are known in advance, I faced challenges when trying to create them dynami ...

Form-linked Progress Bar

This is a little project I created (for fun and learning purposes, even though it may not be the most optimized solution). If you're interested, here's the link to the code: https://codepen.io/paschos/pen/xxGXMQb I'm currently seeking assi ...

Ways to verify AJAX Response String when data format is specified as JSON

When using AJAX to retrieve JSON data from a webpage, it's essential to set the responseType to json. If the data processing is successful, a valid JSON string is returned, which works perfectly. However, if there's an error on the webpage, inst ...

What are some effective ways to optimize a chat application and reduce the strain on the server?

I once created a Python app that allowed users to create chat rooms using a simple REST API server. The client would send requests to the server, which would then respond appropriately. These responses were received by a JavaScript client that continuous ...

Creating dynamic animations by shifting the hue of an image on a canvas

Recently, I've been exploring the world of canvas tags and experimenting with drawing images on them. My current project involves creating a fake night/day animation that repeats continuously. After trying various approaches like SVG and CSS3 filters ...

Creating a JavaScript function triggered by a click event that will redirect to

I'm attempting to create an onclick function that will redirect you to a new page when you click on a div element, much like the A + href attribute in HTML. Any suggestions on how to achieve this? Should I just add an A tag inside the div? I'm un ...

Utilizing external imports in webpack (dynamic importing at runtime)

This is a unique thought that crossed my mind today, and after not finding much information on it, I decided to share some unusual cases and how I personally resolved them. If you have a better solution, please feel free to comment, but in the meantime, th ...

Dynamically add onClick events using JavaScript to perform multiple identical actions

While I can't provide all the code here, I believe this snippet can illustrate my issue: for(var i = 0 ; i < 5 ; i++) { $('#mybutton').on('click', function() { return false; }); $('#mybutton').on('click&apo ...

Having trouble getting the onClick event to trigger in React?

I have a button in my navbar that triggers a submenu (list of items) to display when clicked. Each item is a separate child component and I want them to trigger an event when clicked. However, the onClick event listener does not seem to be working. Other m ...

Having trouble connecting the controller variable in AngularJS to the HTML page

I'm struggling with a simple query that doesn't seem to be working for me. When making an Ajax call and retrieving data from the backend, everything seems to be in order. Here's the code snippet: $.ajax({ type: "GET", url: service ...

Bootstrap not being recognized in AngularJS HTML

I've been working on learning AngularJS, but unfortunately I can't seem to get any Bootstrap themes to show up in my web application. Here is the HTML code for the header that I've been trying: <nav class="navbar navbar-default"> ...

The mobile button bar on iPhone is shown when scrolling or jumping up to the anchor, but it doesn't actually scroll or jump to the

My goal is to include a back-to-top button that remains fixed at the bottom of the browser window. Surprisingly, when clicked, it successfully scrolls to the top in desktop and Android browsers but fails to do so on iPhones. On an iPhone, clicking the butt ...

Internet Explorer 11 and the process of URL encoding

Hello there! I am currently working on an MVC project with Angular where I am utilizing a JsonResult to return JSON data from a list containing emails with a specific date. Below is the AJAX call I'm making from Angular: myApp.service('mailServ ...

The Problem with TypeScript Union Types

I recently started using TypeScript and ran into an issue with a similar scenario. Despite my efforts, I encountered two errors that I can't seem to figure out. If anyone has any insights on how to resolve this, I would greatly appreciate the help! in ...