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

Is it possible for a listener in a component to listen for an $emit coming from a mixin?

Is it possible for my global mixin to broadcast data to various components? I have tried listening for the custom event from the created (or mounted) event inside the component but it doesn't seem to work. For example: Inside the mixin ... methods: ...

The addListener method in Google Maps iterates n times for a specific number of repetitions

When looking at the code below, the GetPropBasedOnRadius(); method loops for a certain number of times. I want to call that method only when the dragging event is completed. However, I am unsure how to do this. Any assistance on this matter would be great ...

Issue with scroll animation across multiple div elements

I am working on a project where I have two main divs, one with the id of "left-div" and the other with the id of "right-div". In the "left-div", there are multiple nested divs each with their own unique id. The overflow-y property of the "left-div" is set ...

What is the best way to export my mongo schema to a file and then utilize it for inserting data?

I've been encountering difficulty when attempting to insert data into my collection. I'm not entirely sure if I'm doing it correctly, so I apologize for the vague request. Hopefully, by providing you with my code, you can help me understand ...

Vue-Router with pagination buttons

I am currently using a basic pagination system for my search results: <ul class="pagination" v-if="lastPage > 1"> <li v-for="pageNumber in lastPage"> <router-link :to="{params: {page: pageNumber}}">${pageNumber}</route ...

Step-by-step guide to aligning layout using material design in generator-gulp-angular

I am currently using generator-gulp-angular with angular-material-design and ui-router All views are loaded into index.html in the <div ui-view></div> element However, when I attempt to center the element with material design directives insid ...

Retrieve the chosen option index using AngularJS

It is common knowledge that a select list can have multiple options, each starting from [0]. For example: [0]<option>E.U</option> [1]<option>India</option> [2]<option>Peru</option> In my Angular application, I am using ...

Troubleshooting Tips for Node.js and MongoDB Socket Closure Issue

I'm running into an issue while working on the login system for my NodeJS application. Everytime I attempt to retrieve a collection, MongoDB throws me this unusual error. The Error Message [MongoError: server localhost:27017 sockets closed] name: &a ...

Deciding whether an item qualifies as a Map in JavaScript

I have been working on developing a function that will return true if the argument provided to it is an instance of a JavaScript Map. When we use typeof new Map(), the returned value is object and there isn't a built-in Map.isMap method available. H ...

Find the difference between the sum of diagonals in a 2D matrix using JavaScript

I'm currently practicing on hackerrank and came across a challenge involving a two-dimensional matrix. Unfortunately, I encountered an error in my code implementation. 11 2 4 4 5 6 10 8 -12 The task at hand is to calculate the sum along the primary ...

Exploring the capabilities of batch updates in Firestore with the latest web version-9

I am facing issues when trying to update certain values in my firestore collection within my nuxt project. const batch = writeBatch(firestore); const data = query(collection(firestore, `notifications`, `${uid}/news`)); const querySnapshot = await ...

Is there a way to store a JSON object retrieved from a promise object into a global variable?

var mongoose = require('mongoose'); var Schema = mongoose.Schema; const NewsAPI = require('newsapi'); const { response } = require('express'); const newsapi = new NewsAPI('87ca7d4d4f92458a8d8e1a5dcee3f590'); var cu ...

Grouping items by a key in Vue and creating a chart to visualize similarities among those keys

I am working with an object that has the following structure; { SensorA: [ { id: 122, valueA: 345, "x-axis": 123344 }, { id: 123, valueA: 125, "x-axis": 123344 }, { id: 123, valueA: 185, "x-axis": 123344 }, { ...

Is transforming lengthy code into a function the way to go?

I have successfully implemented this code on my page without any errors, but I am wondering if there is a more concise way to achieve the same result. Currently, there is a lot of repeated code with only minor changes in class names. Is it possible to sh ...

Navigating through asynchronous transactions in Node.js: A Guide

My application utilizes Nodejs, Mongodb, and amqp. The main module receives messages from amqp, processes them by saving message information into mongodb within a message transaction, and executes additional logic. function messageReceiverCallback(msg) { ...

Angular - Enhance ngFor index while filtering

I am currently working with a list that utilizes an *ngFor loop in the template: <li *ngFor="let product of products | filterProducts: selectedFilter; index as productId"> <a [routerLink]="['/product', productId]"> {{produc ...

ArangoDB's graph maxDepth setting causing excessive iterations

I am working on creating a substantial social network graph using ArangoDB. The database currently contains approximately 35,000 vertices connected by around 150,000 edges. Considering the extensive amount of data, I was looking to display only a portion ...

Embedded tweets may occasionally lose their borders when viewed on various web browsers

My goal is to showcase a collection of responsive embedded tweets in rows of 2. Here are the key elements of the code that have enabled me to achieve this: HTML <div id="tweets"></div> <script src="https://platform.twitter.com/widgets.js" ...

What is the best way to extract valid objects from a string in JavaScript?

Currently, my data is being received through a TCP connection. To determine if a string is a valid JSON object, we use the following method: let body = ''; client.on('data', (chunk) => { body += chunk.toString(); try { ...

Are there any libraries available that can assist with managing forms similar to how Google Contacts handles them

By default, Google Contacts has a feature where the form displays values with some of them being read only. However, when you click on a value, it converts the field into an editable form so you can easily make changes. After editing and pressing enter, th ...