Unexpected reduce output displayed by Vuex

In my Vuex store, I have two getters that calculate the itemCount and totalPrice like this:

 getters: {
    itemCount: state => state.lines.reduce((total,line)=> total + line.quantity,0),
    totalPrice: state => state.lines.reduce((total,line) => total +
        (line.quantity*line.product.price),0)
},

These getter values are displayed in a component as follows:

<template>
<div class="float-right">
    <small>
        Your cart:
        <span v-if="itemCount > 0">
            {{ itemCount}} item(s) {{ totalPrice | currency}}
        </span>
        <span v-else>
            (empty)
        </span>
    </small>
        <b-button variant="dark"
                  to="/cart"
                  size="sm"
                  class="text-white"
                  v-bind:disabled="itemCount === 0">
            <i class="fa fa-shopping-cart"></i>
        </b-button>
</div>
</template>

<script>
    import {mapGetters} from "vuex";
    export default {
        name: "cart-summary",
        computed: {
            ...mapGetters({
                itemCount: "cart/itemCount",
                totalPrice: "cart/totalPrice"
            })
        }
    }
</script>

<style scoped>

</style>

While the second getter (totalPrice) functions correctly by displaying the total price in the cart, the first one (itemCount) shows strange results. For example:

If my cart has 3 items of product A, the total will display as 03. If my cart has 3 items of product A and 2 of B, the total will display as 032.

Answer №1

Since Javascript is a loosely typed language, it has a tendency to coerce data types, resulting in unexpected behaviors especially with math operations. For instance, 1 + "1" === "11".

If the value of line.quantity is stored as a string, using parseInt(line.quantity) will give you the desired numerical value.

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

The Google Chrome console is failing to display the accurate line numbers for JavaScript errors

Currently, I find myself grappling with debugging in an angular project built with ionic framework. Utilizing ion-router-outlet, I attempt to troubleshoot using the Google Chrome console. Unfortunately, the console is displaying inaccurate line numbers mak ...

Tips for accessing and adjusting an ngModel that is populated by an attribute assigned via ngFor

Looking for guidance on how to modify an input with ngModel attribute derived from ngFor, and update its value in the component. Here is my code snippet for reference: HTML FRONT The goal here is to adjust [(ngModel)] = "item.days" based on button click ...

What methods could I use to prevent the WYSIWYG buttons from automatically linking?

I've been working on creating an editor but I'm facing a small issue. Every time I click on a button (such as bold or italic), it follows a link instead of performing the desired action. Here's a snippet of what I've tried so far: fu ...

What is the best approach to breaking down attributes upon import according to the theme?

Hey there! Here's the thing - I have this file called <code>colors.ts:

export const black = '#0C0C0C'; export const blue = '#22618E'; Whenever I need to use a color, I import it like so: import {black} from 'Shared& ...

Encountering a "Connection Refused" error when attempting to test a React and Express application

Currently, I am developing an order system using React for the frontend (port 3000) and Express for the backend (port 3001). Everything functions perfectly when tested on the same MacBook that hosts the node project. However, when testing it on a differen ...

Combining strings in a JavaScript object

Can someone help me with concatenating strings within an object in JavaScript? I am parsing through an XML file to create a list of links in HTML. Each time I iterate through the loop, I want to add a new <li> element containing the link. How can I ...

Is it possible to organize and filter a dropdown menu in JQuery based on a secondary value (new attribute)?

Can the drop-down list be sorted by value2? <select id="ddlList"> <option value="3" value2="3">Three</option> <option value="1" value2="1">One</option> <option value="Order_0" value2="0">Zero</option> </sele ...

Unable to Click on Selenium Element

When a link is clicked on a website, the URL remains unchanged but a popup appears on the screen containing elements that can only be accessed after running driver.switchTo().defaultContent(). To access these elements, I have used a javascript executor com ...

Unable to access the done property in an AJAX JSON promise

Trying to dive into the world of JavaScript promises. My goal is to create a button that triggers a function displaying the result of a promise from another function. So far, I've been following tutorials and here's where I'm at: function my ...

Lazy loading AngularJS UI router named views is an efficient way to improve performance

AngularJS UI router named views loading based on user access rather than loading at the time of state route access. Example: $stateProvider .state("login", { url: "/login", templateUrl: getTemplateUrl("login/Index") }) ...

Display the same DIV element across various HTML tabs

When two different tabs are clicked, I need to display a set of 10 Search Fields. Both tabs have the same fields, so instead of using separate DIVs, I want to use the same DIV and only change the AJAX REST End-Point based on the selected TAB. Can someone ...

Guide to adding Angular 2 components to various locations in the DOM of a vanilla JavaScript webpage

Scenario: A customer is interested in creating a library of Angular 2 components that offer a technology-agnostic interface to developers. This allows developers to use plain JavaScript without needing knowledge of the internal workings of the library. Th ...

Expanding cards with Material-UI and React seems to be a challenge when using an expander

I've recently integrated a Card component into my project, sourced from material-ui's official website. However, I'm encountering an issue where the CardHeader does not expand upon clicking. This is the structure of my Component : import ...

Show the form when the button is clicked

I want to create an application that allows users to click on a button in the top right corner (check image) to hide one div (topics) and show another div (a form for adding a new topic). Here is what it looks like: https://i.stack.imgur.com/YeRTw.png ...

What is the best way to invoke a method within the onSubmit function in Vuejs?

I am facing an issue with a button used to log in the user via onSubmit function when a form is filled out. I also need to call another method that will retrieve additional data about the user, such as privileges. However, I have been unsuccessful in makin ...

Moving data of a row from one table to another in Laravel by triggering a button click

For instance, consider a scenario where clicking a button moves a row to another table in the database and then deletes it. Implementing this functionality in Laravel seems challenging as I am unable to find any relevant resources or guidance on how to pro ...

Tips on using constructor functions and the new keyword in Typescript

This is a demonstration taken from the MDN documentation showcasing the usage of the new keyword function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } const car1 = new Car('Eagle', 'Talon TSi&apos ...

Tips for including items in a list nested within a dictionary using JavaScript

I'm currently working with a JavaScript dictionary and I need to insert an element into a list that belongs to a specific key within the dictionary. Check out the code snippet below: lines = [ [1,2], [2,4], [2,3], [3,5] ]; nodes = [ ...

Error in Passport JS: Trying to use an undefined function

I've been struggling with debugging my code in Express and Passport. I've tried following solutions from others but can't seem to get it right. Any help or useful links would be greatly appreciated. Here is the error message along with the ...

What is the best way to retrieve data from a JSON object?

Can the status variable be used as a JSON object? What is the method to access the values of action_success and newIndex within the status object? Server: [HttpPost] public ActionResult UploadFiles() { // save file.. return Json(new { action_suc ...