Vue.js computed property: [Vue warn]: Oops, looks like there's a hiccup in the render! Error: "TypeError: Unable to access property 'userId' of an undefined variable"

Just trying my hand at Vue.js, so bear with me if this seems too simple.

I've got the code for Home.vue here:

<template>
  <div class="home">
    <div>
      <b-table striped hover :items="borrowingHistroy"></b-table>
    </div>
  </div>
</template>

<script>
import userData from '@/data/user_data';

export default {
  name: 'Home',
  data() {
    return {
      userId: 0,
    };
  },
  computed: {
    borrowingHistroy: () => userData[this.userId].borrowingHistory,
  },
};
</script>

The code isn't rendering and throwing this error/warning:

[Vue warn]: Error in render: "TypeError: Cannot read property 'userId' of undefined"

Switched the borrowingHistroy as shown below to make it work:

 borrowingHistroy: () => userData[0].borrowingHistory,

Does that mean this is not defined here?

How can I access the userId defined in "data" then?

****** edited ******

This is some other parts of my code:

main.js:

import Vue from 'vue';
import BootstrapVue from 'bootstrap-vue';

import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap-vue/dist/bootstrap-vue.css';

import App from './App.vue';
import router from './router';
import store from './store';

Vue.use(BootstrapVue);

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount('#app');

App.vue:

<template>
<div id="app">
    <img alt="Vue logo" src="./assets/images/HPL.png">
  <div id="nav">
    <router-link to="/">Home</router-link>
  </div>
  <router-view />
</div>
</template>

router/index.js:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

export default router;

store/index.js:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  },
});

Answer №1

It is recommended to pass the component instance as a parameter in arrow function:

  borrowingHistory: (vm) => userData[vm.userId].borrowingHistory,

As per information available on the official documentation :

Keep in mind that when using an arrow function with a computed property, the component's instance will not be accessible directly. However, you can still reference the instance by passing it as the first argument of the function:

computed: {
  aDouble: vm => vm.a * 2
}

Answer №2

An alternative approach is to streamline the computed property definition by utilizing parentheses, ensuring that you retain the context of the application:

 obtainHistory() {
   return userData[this.userId].borrowingHistory
 }

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

Ways to deselect checkboxes and eliminate validation requirements

Below is the HTML code snippet that I am working with: <div class="form-group"> <div class="input-group"> <label for="daterange-vacancy" class="input-group-addon">Van</label> ...

Problem encountered when attempting to return data received from database queries executed within a loop

Having an issue with making multiple MongoDB queries in a loop and trying to send all the results as one data array. However, simply using 'return' to send the data is resulting in 'undefined' and not waiting for the results of all DB r ...

Encountering an issue with receiving "undefined" values while utilizing WordPress post metadata in AngularJS

Utilizing the Wordpress REST API v2 to fetch data from my functional Wordpress website to an AngularJS application. Everything is functioning properly, however when I attempt to access post meta such as "_ait-item_item-data", it returns an error stating "u ...

What is the method to define YAML array indices in JavaScript?

I apologize for my previous post. I have successfully integrated a RapidAPI for Covid-19 updates, which is now outputting the results as an array JSON in the console. You can view the YAML Array Output here. I am now facing a challenge in listing specifi ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

Instructions for activating column resizing in MUI DataGrid

Is there a way to enable column resizing for users in MUI DataGrid? It's enabled by default on XGrid, but I would like to enable it on Datagrid as well. Any assistance is appreciated. <DataGrid className={classes.table} ...

A step-by-step guide on showcasing Flickr images through API using a Justified Gallery

I am looking to integrate the Miromannino Justified Gallery () into my project, but I want it to showcase images fetched from Flickr. I have successfully implemented the code to retrieve photos from Flickr using the API through Ajax: $.ajax({ url ...

The array remains empty despite attempts to push elements into it

How can I ensure that the elements pushed into the "comments" array are visible outside of the initial foreach loop in this code snippet? const Post = require('../models/post'); const Comment = require('../models/comment'); getpost: a ...

The RxDB Angular2-cli error message. "Cannot assign a 'Promise<void>' to a 'Promise<any>' parameter."

https://i.sstatic.net/50vu6.png I've been grappling with getting RxDB to function properly in a fresh project I initiated using the Angular CLI. Here's my process: ng new <Projectname> After that, I installed RxDB by running: npm instal ...

determining the preference between setTimeout and setImmediate

After reading the documentation on the node, it mentions: setImmediate(callback, [arg], [...]) This function is supposed to execute callback immediately after I/O events callbacks and before setTimeout and setInterval However, in practice, I noticed tha ...

Is it possible to change individual pixels within a canvas without the need to duplicate the entire buffer?

Is it possible to directly alter individual pixels within a canvas, rather than retrieving the entire buffer using ctx.getImageData and then pasting it back with ctx.putImageData? This is crucial in order to avoid the costly process of copying data every ...

The issue with the left border color not functioning in JavaScript

Attempting to alter the border-left-color property using this script is resulting in a Uncaught SyntaxError: Unexpected token -. Is border-left-color actually supported? Javascript function logoChange() { var description = new Array (); description[0] ...

Tips on preventing duplicate websocket clients in VueJS

Each time I access a component, it triggers the socket.on event. Additionally, there is a Vuejs button component as shown below. So when I emit to the 'socket.on('voice')' event in nodejs, the nodejs socket emits to the 'socket.on( ...

Starting service upon startup in Angularjs

I am looking to retrieve configuration data from the server and store it in the global scope within my AngularJS application. My app operates in multiple modes such as development and production, with different external services being used depending on the ...

The styling of the React component is not being applied as expected by the .Css file

My title component seems to be having trouble applying the CSS styles as expected. I'd like it to have a green background, but for some reason, it's displaying as white. Below is the Component Js file: import React from "react"; funct ...

Utilizing dynamically assigned ng directives in my unique custom directive

I'm in the process of creating a customized table element that looks like this: <datatable items='tableItems' columns='columnsConfig' /> Here, 'tableItems' represents my array of items and 'columnsConfig&apos ...

When scrolling, the fixed menu bar at the top of the page is making the content below jump

I am attempting to create a fixed submenu that sticks to the top of the page when scrolling, but I am encountering some issues. The current code I have is as follows: $(window).scroll(function () { if ($(window).scrollTop() > 175) { $('#loca ...

How can I stop a table from resizing in Tailwind CSS?

So, I have created this table <table class="table-fixed border-separate border border-green-800"> <thead class="bg-indigo-800 border-b-2 border-indigo-200 w-full"> <tr> <th ...

Modify the property of an element during execution

I am tasked with developing a button that can change the type of a chart component (e.g., from columns to pie) upon clicking. However, I am unsure how to implement this functionality within the component structure. The goal is to modify the :series-default ...

Verify if a certain value is present within a nested array

I need assistance with checking if a specific value is present within a nested array. Here is an example of the data I am dealing with: [ { name: 'alice', occupation: ['Artist', 'Musician'], }, { ...