Encountering difficulty when determining the total cost in the shopping cart

I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly.

Here is my current logic:

Data structure for Products,

product = {
      'productName': 'Sample Product',
      'productImage': productImage,
      'rate': 100,
      'quantity': 1
    }

this.addToCartService.cartItems.subscribe(product => {
  if (product) {
    const productExistInCart = this.cartItems.find(({ productName }) => productName === product.productName);
    if (!productExistInCart) {
      this.cartItems.push(product);
      return;
    } else {
      productExistInCart.quantity++
    }
    this.totalPrice = this.cartItems
      .map(item => item.rate)
      .reduce((prev, curr) => prev + curr, 0);
  }
});

HTML Structure

 <div class="cart_box dropdown-menu dropdown-menu-right show">
    <ul class="cart_list" *ngIf="cartItems.length">
      <li *ngFor="let cartItem of cartItems; let i = index">
        <a (click)="removeFromCart(i)" class="item_remove"><i class="ion-close"></i></a>
        <a href="#"><img src="{{cartItem.productImage}}" alt="cart_thumb1">{{cartItem.productName}}</a>
        <span class="cart_quantity"> {{cartItem.quantity}} x <span class="cart_amount"> <span
              class="price_symbole">₹</span>{{cartItem.rate}}</span></span>
      </li>
    </ul>
    <div class="cart_footer">
      <p class="cart_total">Total: <span class="cart_amount"> <span
            class="price_symbole">₹</span>{{totalPrice}}</span>
      </p>
      <p class="cart_buttons"><a href="cart.html" class="btn btn-default btn-radius view-cart">View Cart</a><a
          href="checkout.html" class="btn btn-dark btn-radius checkout">Checkout</a></p>
    </div>
  </div>

I'm currently stuck and unsure how to update the total of existing items in the cart. Any help would be appreciated.

Current Output Shown Below

https://i.sstatic.net/luVDF.png

In the image above, the total should be 400 but it is displaying as 100. There seems to be an issue with the calculation.

Answer №1

The issue arises from failing to consider the quantity when computing the total cost. To address this, implement the following solution:

        this.totalPrice = (this.cartItems
          .map(item => item.rate * item.quantity)
          .reduce((prev, curr) => prev + curr, 0));

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

Which is quicker: retrieving data from an array or an SQL table in PHP?

In my possession are a series of md5 hashes, each linked to a specific file name. Within a PHP array structure, I would access the information in this manner: $md5['filename']. Conversely, if stored within an SQL table, I would retrieve it throug ...

A guide on how to associate data in ng-repeat with varying indices

Here is the data from my JSON file: var jsondata = [{"credit":"a","debit":[{"credit":"a","amount":1},{"credit":"a","amount":2}]}, {"credit":"b","debit":[{"credit":"b","amount":3},{"credit":"b","amount":4},{"credit":"b","amount":5}]}, {"credit":"c","debi ...

What's preventing me from invoking this object's function through an inline anchor?

CSS: <div class="box"> <p>This is a box</p> </div> Javascript: var box = { content : (function() {return ("This is the content of the box")}) }; alert("Box content: \n" + box.content()); $("output").text( +"<br/ ...

Ways to simulate a function that is a part of an internal object

Is there a way to mock a method from an object within my UnderTest class? When the Update method is triggered by an event from a child component, I need to mock the service.saveNewElement(data) method in order to test data in the then() block. <script ...

A beginner's guide to crafting a knex query with MySQL language

Within MySQL Workbench, I currently have the following code: USE my_db; SELECT transactions.created_at, price FROM transactions JOIN transactions_items ON transactions.id = transactions_items.transaction_id JOIN store_items ...

Experimenting with Nuxtjs application using AVA and TypeScript

I'm in the process of developing a Nuxt application using TypeScript and intend to conduct unit testing with AVA. Nonetheless, upon attempting to run a test, I encounter the following error message: ✖ No test files were found The @nuxt/typescrip ...

Showing error messages in Angular when a form is submitted and found to be invalid

My form currently displays an error message under each field if left empty or invalid. However, I want to customize the behavior of the submit button when the form is invalid. <form #projectForm="ngForm" (ngSubmit)="onSubmit()"> ...

Getting the iframe onload event in an ASP.NET application

I have integrated ReportViewer to display SSRS reports on my .aspx page. However, since the ReportViewer is rendered as an iframe in the browser, I am looking for a way to trigger a JavaScript function every time the iframe loads. Using window.onload w ...

Utilize moment.js to format a datetime and display the corresponding timezone

I'm having trouble displaying timezones correctly using moment.js. I attempted to use the following code: var result = moment(someDate).format("MM/DD/YYYY HH:mm A Z"); This returns something like: 08/05/2015 06:18 PM +02:00, which is okay, but I w ...

How can I extract specific information from a JSON Array?

I need to retrieve specific data from a JSON array on the server. The problem is that I only want the data with a particular CHEF_NAME. Currently, I am working on this in Android Studio. JSON Array [{"status":"Success","recpie":[{"id":" ...

Uncovering hidden links in a menu with Python Selenium and JavaScript

Can someone provide guidance on how to activate the JavaScript submenu associated with this button, "x-auto-54"? <table id="x-auto-54" class=" x-btn avtar-x-btn x-component x-btn-noicon x-unselectable " cellspacing="0" role="prese ...

Angular ngFor does not display the JSON response from the API (GET request)

I'm attempting to retrieve a JSON response from my API and display the values on my Angular page using ngFor. Although I don't have any build errors, the values are not being displayed on the page. They only appear in the console when using cons ...

Tips for determining the width of an image and utilizing that measurement as the height in order to create a balanced square image

I am currently facing an issue with my code that is used to retrieve the width of an image which is set in percentages. Although I am able to obtain the width in pixels, I am struggling with correctly inserting the variable into the CSS property value usin ...

What is the best way to create transitions for item entry and exit in ReactJS without relying on external libraries?

I am looking to create an animation for a toast notification that appears when a user clicks on a button, all without the use of external libraries. The animation successfully triggers when the toast enters the screen upon clicking the button. However, I e ...

How should one properly address an HTTP error situation?

Present situation: I am currently working on a service.ts file that saves data in the backend: public update(route: string, values: Array<any>): Observable<boolean> { let body = { values: values }; return this.httpClient.put(route, bo ...

Dynatree fails to consider the select feature while utilizing ajax requests

Currently, I am utilizing the dynatree plugin to exhibit a checkbox tree in multi-select mode (mode 3). Upon initializing the tree using ajax (without lazy loading), it appears that certain nodes that were initially loaded as selected are forgotten. When ...

Begin the Wordpress AJAX Login

Is there a way to trigger the code below when a user is logged out from another location due to user inactivity, similar to how wp-admin displays an AJAX login overlay if a user is logged out? I have not come across any documentation or tutorials on achiev ...

Interacting with APIs in Svelte applications

I'm fairly new to utilizing Svelte and JavaScript. I've been attempting to construct a page that incorporates numerous API components from external websites, but I'm facing some challenges. I'm uncertain about where exactly to place the ...

What is the best way to compare two TypeScript object arrays for equality, especially when some objects may have multiple ways to be considered equivalent

Currently, I am in the process of developing a cost function for a game where players are given a set of resources in their hand. The resources can be categorized into different types such as Fire, Air, Water, Earth, Good, Evil, Law, Chaos, and Void. Thes ...

Angular Universal (SSR) 'Selectors were not applied as rules were not followed'

Steps to Reproduce: ng new testproject --style scss cd testproject ng add @ng-bootstrap/ng-bootstrap npm run build This issue is not limited to ng-bootstrap, it can occur with other frameworks like bootstrap or tailwind that use SCSS. Error Description: ...