Home » vue » Vue Reduce method function is not working

Vue Reduce method function is not working

Posted by: admin November 26, 2021 Leave a comment


I’m trying to calculate the total balances returned from the array of objects of clients stored in Firebase.

I’m using Vue for this project. Right now, it’s not working as it’s returning NaN

computed: {
    totalOwed() {
      if (this.clients && !this.loading) {
        // console.log(this.clients);
        this.clients.reduce((total, client) => {
          return total + parseFloat(client.balance.toString());
        }, 0);
      return null;
    ...mapState(["clients", "user", "loading"])

When I used the totalOwed computed property in the template, I got a NaN as the value.
Here is the Github link and Live site

Code can be found in the Clients.vue inside of src/components/clients directory


You are using wrong data structure. Shouldn’t it be client.balance.stringValue?

-  return total + parseFloat(client.balance.toString()); // delete this line
+  return total += parseFloat(client.balance.stringValue); // add this line

Plus add return before this.clients.reduce...