During the rendering process, a referenced computed property is not defined on the instance

Description:

In my child component, I am working with an array called expenseButton that is passed as props. The array contains objects with values which I need to calculate the sum of using the array.reduce() method.

Issue:

While I can successfully get the sum using standard methods, when I try to convert it into a computed property, I encounter the following error message:

Property or method "test" is not defined on the instance but referenced during render

<script>
export default {
  props: {
    expenseButton: Array,
  },
  data() {
    return {
      chosenExpenseId: null
    };
  },
    computed: {
      test() {
        return this.expenseButton.reduce((acc, curr) => {
          acc += curr.expensesValue;
          return acc;
        }, 0);
      }
    }
  }
};
</script>

<template>
<div>
<div class="yourBalance">
      Your monthly balance
      <br />
      <span>${{ test }}</span>
    </div>
</div>
<template>

Additional Info

The "expensesValue" property in the "expenseButton" array is fetched from a backend database using axios

Parent Component

<template>
<div>
   <expense-button :myExpense="myExpense" :expenseButton="expenseButton"></expense-button>
</div>
</template>

<script>
import Expenses from "../components/expenses.vue";
import axios from "axios";

export default {
  components: {
    "expense-button": Expenses
  },
  data() {
    return {
      budgetOwner: "",
      myExpense: [],
      expenseButton: [],
      component: "",
      errored: false
    };
  },
beforeRouteEnter(to, from, next) {
    axios
      .get("/api/budget", {
        headers: { "Content-Type": "application/json" },
        withCredentials: true
      })
      .then(res => {
        next(vm => {
          if (res.data.budget.length > 0) {
            vm.myExpense = res.data.budget;
            vm.expenseButton = res.data.budget[0].expenses;
          } 
        });
      })
      .catch(err => {
        next(vm => {
          console.log(err.response);
          vm.errored = true;
        });
      });
  }
}
</script>

Data Retrieved from Database

"budget":[{"expenses":[

{"expensesKey":"a","expensesValue":1,"subExpenses":"","newValue":""},

{"expensesKey":"b","expensesValue":2,"subExpenses":"","newValue":""},

{"expensesKey":"c","expensesValue":3,"subExpenses":"","newValue":""}

]

Answer №1

Check out this solution

calculateTotalExpense() {
    if(this.expenseButton){
        return this.expenseButton.reduce((total, current) => {
          total += current.expensesValue;
          return total;
        }, 0);
      }
    else{
        return 'No expenses available';
    }
}

Answer №2

Seeking to offer assistance. The issue seems to be related to curr.expensesValue. What exactly is expensesValue? Also, have you properly mounted your app? Does the root element have the same id as el:'#app' and div#id in my example?

new Vue({
  el: "#app",
  data:{
  expenseButton:[1,2,3,4,5],
      chosenExpenseId: null
  },
    computed: {
      test() {
        return this.expenseButton.reduce((acc, curr) => acc + curr)
      }
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div class="yourBalance">
      Your monthly balance
      <br />
      <span>{{ test }}</span>
  </div>
</div>

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

Encountering an unspecified array type when making an Ajax request with JSON

Currently, I am developing a web application that allows users to play sudoku with a Java back-end. To communicate with my jQuery using Ajax, I have created a servlet. Upon sending the generated array (the sudoku) to my web application through this servle ...

ExpressJS route encountering issues with GET method functionality

I'm facing an issue with my code where the function is not running inside the specific routing when trying to retrieve data using /:user. Can someone help me identify the mistake in the following implementation? const express = requi ...

Issue arises after injecting HTML element into the DOM due to memory constraints and display inconsistencies

Upon executing the following script in Firefox... var d = $("<div class='test'></div>"); d.hide(); $("body").prepend(d); d.show(); ...and examining the HTML, the inserted element will have the style attribute: style="display: blo ...

When the application is converted into static files, the dynamic routes fail to function properly

I have a website that is statically exported but has dynamic routes. During development, the site works fine. However, when I build and export it, then serve the static files using serve, an issue arises. If you go to the site root and click on a link th ...

Maxlength and Minlength attributes are not considered when using input type=“number”

Why is the maxlength attribute not functioning properly for this input element? <input type="number" maxlength="5" maxlength="10" /> ...

Challenges with Asset Management in Vite Compilation Result

I'm encountering a problem with structuring assets in the output directory while utilizing Vite for my project. I have set up the output.assetFileNames option to categorize assets into subfolders based on their types (css, fonts, img, js), but it&apos ...

Categorizing the types of dynamically retrieved object values

I've developed a unique class with two properties that store arrays of tuples containing numbers. Additionally, I've implemented a method called "getIndex" which dynamically accesses these properties and checks for duplicate number values within ...

Tips for including a Places Autocomplete box within an InfoWindow on Google Maps

I am currently working with the Google Maps Javascript API v3 and I am facing a challenge. I want to integrate a Places Autocomplete box inside an InfoWindow that pops up when a user clicks on a marker. I have successfully created an autocomplete object a ...

Achieve Dual Functionality with Vue.JS Button within a Parent Element

My parent component structure looks like this: <template> <b-container> <b-modal id="uw-qb-add-item-modal" ref="uw-qb-add-item-modal" title="Enter Item Number" @ok="handleNewItem"> <f ...

Getting the total number of child elements in a web page using Selenium web-driver with Node.js

I've been looking everywhere, but I can't seem to find the answer Here's my HTML code: <form id="search_form_homepage" > ... <div class="search__autocomplete" style="display: block;"> &l ...

Utilizing Loopback Callbacks within a Looping Structure

While working in a for-loop, I encountered an issue where I needed to access the loop variable 'i' from within a callback function but it was not accessible due to closure restrictions. Despite attempting different methods such as using (i) or ca ...

Comparison of Angular.js formsets to Django's formset

Within Django, formsets allow for the use of multiple forms within one larger form. For example, you can add multiple books to a library formset by repeating the same book form with details such as author and title. I am looking to achieve similar functio ...

Issue with Vue/Laravel 5.3: Component template is not displaying on the view

Deciding to incorporate a Vue component into my view for the first time has presented some challenges. I've created a file called assets/js/components/ImageUpload.vue with the following content: <template> <div> <div v-if="!image"> ...

The TypeScript rule in the project-specific .eslintrc.js file is not being applied as expected

Currently, I am following a tutorial on Ionic/Vue 3 which can be found here. However, when I try to serve the project, I encounter the following error: https://i.stack.imgur.com/k4juO.png It appears that my project-level .eslintrc.js file is not being ap ...

Asynchronous NestJs HTTP service request

Is there a way to implement Async/Await on the HttpService in NestJs? The code snippet below does not seem to be functioning as expected: async create(data) { return await this.httpService.post(url, data); } ...

The Proper Method of Displaying Data from a JSON File Using AngularJS

I'm having trouble getting the data from a JSON file (click on the "Json File" link to view the structure). I'm not sure what to put after "$Scope.listOfRecipe=". I tried using response.data.recipes, but it's not working and causing errors. ...

problem arising from the origin preventing me from utilizing localStorage in conjunction with JSDOM

Currently, I am facing an issue while trying to load a webpage in a node environment using JSDOM. The webpage relies on localStorage for its functionality. I have attempted to load the webpage by utilizing JSDOM's URL configuration option and accessi ...

Issue with Apollo Client - Mutation failing due to undefined property 'data'

When attempting to call a mutation on the client side in Next.js, I encounter an error every time I use the useMutation hook or the client itself, resulting in the following error: Cannot read property 'data' of undefined. See the code snippets b ...

Enable JSON Data Management through Express

I am utilizing the lowDB dependency to manage JSON data in conjunction with Express, and for the most part, it is functioning properly. However, I have encountered a bug that I am struggling to resolve. I have created a /create page where users can input ...

How to apply an icon image using the background property in CSS in Vue 3

Need help setting background image from the public folder |_public | |_images | |_icon.png |_src |_components |_TheHeader.vue I'm having difficulty trying to set an image as a background in TheHeader.vue using CSS, but the image is located in ...