What causes the "Cannot read properties of undefined" error in Vue when an array is initialized and output is still being displayed?

I am working with two vue files, namely App.vue and a component called UsersPage.vue.

UsersPage.vue:

<script>
export default {
    data:() =>({
        usersList : []
    }),
    methods:{
        async createUsersList(){
            this.usersList = await fetch("https://jsonplaceholder.typicode.com/users").then((response)=> response.json());
        }
    },
    created(){
        this.createUsersList();
    }
}
</script>

<template>
    <ul>
    <li v-for="user in usersList" :key="user.id"><b>Name:</b>{{user.name}}, <b>UserName:</b> {{user.username}},<b>ZipCode:</b> {{user.address.street}} </li>
    </ul>
</template>

and App.vue:

<script>
import UsersPage from "./components/UsersPage.vue"

export default {
  components: {
    UsersPage,
  },
  data: () => ({
    currentPage: "Home",
  }),
  methods: {
    showHomePage() {
      this.currentPage = "Home";
    },
    showLoginPage() {
      this.currentPage = "Login";
    },
  },
};
</script>

<template>
  <header class="header">
    <span class="logo">
      <img src="@/assets/vue-heart.png" width="30" />C'est La Vue
    </span>
    <nav class="nav">
      <a href="#" @click.prevent="showHomePage">Home</a>
      <a href="#" @click.prevent="showLoginPage">Login</a>
    </nav>
  </header>

  <UsersPage/>
</template>

Although the output is displayed correctly without any errors when I run this, changing the usersList to an array with elements such as usersList:[1,2], still renders the data properly but results in the following error in the browser console:

Uncaught TypeError: Cannot read properties of undefined (reading 'street')
    at UsersPage.vue:19:149
    at renderList (runtime-core.esm-bundler.js:2894:22)
    at Proxy._sfc_render (UsersPage.vue:19:163)
    at renderComponentRoot (runtime-core.esm-bundler.js:902:44)
    at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:5615:57)
    at ReactiveEffect.run (reactivity.esm-bundler.js:187:25)
    at instance.update (runtime-core.esm-bundler.js:5729:56)
    at setupRenderEffect (runtime-core.esm-bundler.js:5743:9)
    at mountComponent (runtime-core.esm-bundler.js:5525:9)
    at processComponent (runtime-core.esm-bundler.js:5483:17)

This raises the question why this error occurs even though the data is rendered correctly and the address field does exist in https://jsonplaceholder.typicode.com/users?

Answer №1

Within your v-for loop, you are referencing users.address.street.

When passing an array like [1, 2] to the usersList and Vue processes them with the v-for, it tries to access the address.street of these numbers.

Since numbers do not have an address property, it returns as undefined. Consequently, trying to access any property of undefined results in the error you encountered.

Note: To prevent errors when parsing items without an address, consider using users.address?.street instead of users.address.street.
Refer to: nullish coalescing operator.


Additionally, avoid naming your iterator users as it may create confusion for yourself or other developers working on the code. It is recommended to name it user (e.g.,

v-for="user in usersList" :key="user.id"
).
However, this does not change the fact that you cannot access its address.street property when dealing with a number.

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

Tips for resolving issues with mat-autocomplete during scrolling

When I open the mat-autocomplete and scroll down the page, I would like for the mat-autocomplete to stay in place. ...

Function in Node.js/JavaScript that generates a new path by taking into account the original filepath, basepath, and desired destination path

Is there a custom function in Node.js that takes three arguments - filePath, basePath, and destPath - and returns a new path? For example: Function Signature Example var path = require('path'); // Could the `path` module in Node be useful here? ...

Error: Unable to locate corresponding closing tag for "<%"

I'm struggling to figure out what I might have missed. Everything appears correct, but the nested and somewhat complex code that I am writing seems to be causing an issue with EJS. The variable posts has been passed from node.js to the EJS file. How c ...

Clearing Input Values in Text Boxes, Dropdowns, and Checkboxes in ASP.NET MVC

Currently, I am working with Asp.net MVC 4 using C#. On one of my pages, I have a Text box, Drop down, and checkbox all together as search filters. There is also a "Clear" button to reset the values. When this button is clicked, I want the textbox value to ...

A guide to finding the mean in Angular by utilizing JSON information

import { Component, OnInit } from "@angular/core"; import { MarkService } from "../app/services/marks.service"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"] }) export class AppComp ...

Mastering advanced String templating using loops and control statements in Javascript

During runtime, I receive an array similar to the example below: var colors = ['red', 'green', 'blue']; I then need to create a JSON String that looks like this: { "color" : { "name" : "foo", "properties ...

Exploring the possibilities of working with deeply nested components in React recursively

I have a basic to-do list with functionality for adding todos, toggling completion status, and deleting todos. My goal is to have the ability to nest todos infinitely. I've been able to display nested todos through recursion, but I'm struggling t ...

Tips on effectively implementing vuedraggable to manage nested components responsible for handling data within nested arrays of data stored in Vuex

I am currently working with a system where I have a collection of items, each of which can contain its own nested list of items that can go to any depth. These items are draggable within the list of object trees and the data is managed using Vuex. The drag ...

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. Is the ...

Traverse each child element sequentially using setTimeout or a delay function

Looking to dynamically apply a CSS filter to a list of divs with a delay between each iteration. Here are my attempted solutions: $(this).children().each(function() { $(this).delay(5000).css("-webkit-filter", "brightness(2)"); }); And this alternativ ...

Switch between pages within a reactjs application by utilizing react router

Greetings! I am currently diving into the world of reactjs and experimenting with navigation from one page to another by simply clicking on a link through react router. In my home.js file, I have listed out some interesting places and I aim to click on one ...

Issue persists: Ajax functionality remains nonfunctional, prompting the need for

My goal is to use the post input, and upon hitting enter, I want to dynamically replace <div id="mainPagePosts"></div> with new data without causing a page refresh. However, even after submitting the post, the page still refreshes, although I d ...

Issue with Jquery Drag and Drop functionality, navigate to a different page

I am trying to incorporate a page with js from quotemedia.com using Jquery. When I insert the js into the sortable, and then drag and drop the element containing the js, it suddenly switches to full page display. This issue occurs in Firefox, but IE works ...

Alert: An invalid value of `false` was received for the non-boolean attribute `className`. To properly write this to the DOM, please provide a string instead: className="false" or use a different

While many have tried to address this issue before, none of their solutions seem to work for me... The error I am encountering is: If you want to write it to the DOM, pass a string instead: className="false" or className={value.toString()}. If ...

I require the ability to retrieve only the data from a UI grid column, specifically based on the column name selected

I need help with my angularjs application that utilizes Ui grid. There is an external dropdown menu located outside of the ui grid, which lists all the column names in the grid. I want to be able to select a specific column name from this dropdown and retr ...

developing a custom modal using a button in a React project with Material UI

Hello everyone, I have a question regarding React. I am fairly new to React and need some assistance with adding a new function that creates a Modal. I want to call this function onClick when the add icon is pressed (line 43). Any help would be appreciated ...

Dissecting Distinct and Alphabetized Attributes in JSON/JavaScript

Below is a code snippet that retrieves and organizes a list of values from JSON data in alphanumeric order based on a specific key-value pair: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 &a ...

Navigating arrays containing arrays/objects and updating properties in Angular using loops

My challenge involves an array containing arrays and objects. Within a function, I am attempting to assign a value to a specific property (for example, setting 'call' of $scope.companies[0].users to the value selected in a checkbox). Despite my r ...

Using php variable to pass data to jquery and dynamically populate content in jquery dialog

I am facing challenges trying to dynamically display MySQL/PHP query data in a jQuery dialog. Essentially, I have an HTML table with MySQL results. Each table row has an icon next to its result inside an anchor tag with the corresponding MySQL ID. echo &a ...

What is the official name of the key type for the Built-in Object?

There was a built-in type that I used in the past which represented the union of all possible object keys. It was named objectKey or something similar. Here is an example: type objectKey = string | number | symbol Unfortunately, I am drawing a blank on t ...