Unable to display nested JSON data from API in Vue.js

Having trouble accessing nested properties from API JSON data.

The Vue component I'm working on:

var profileComponent = {
    data : function() {
        return {
            isError : false,
            loading : true,
            users : null,
            activeUser : '',                
        }
    },
    mounted() {
        axios
        .get('https://jsonplaceholder.typicode.com/users')
        .then(response => (this.users = response.data))
        .catch(error => {console.log(error);this.isError = true})
        .finally(() => {console.log('GET request from users');this.loading = false})
     },
    template : `
    <div class="profile">
        <div v-if="isError">
            <h3>There was an error</h3>
        </div>
        <div v-else-if='isLoading'>
        Loading
        </div>
        <div v-else>   
                <select v-model="activeUser">
                    <option v-for="user in users" v-bind:value="user">{{ user.name }}</option>
                </select>          
        </div>
        <div class="temp">
            <p>{{ activeUser.address.street }}</p>
        </div>
    </div>
`}

The issue arises when trying to access {{ activeUser.address.street }}, which doesn't work. However, changing it to {{ activeUser.address }} makes it function properly. The JSON data retrieved from jsonplaceholder website does contain the street property, so what could I be missing?

Answer №1

When the activeUser is an empty string by default, trying to access activeUser.address will result in it being undefined. If you attempt to use activeUser.address.street, an error will occur.

To resolve this issue, you can use:

<p>{{ (activeUser && activeUser.address)? activeUser.address.street : ''}}</p>  

Instead of just:

<p>{{ activeUser.address.street }}</p>

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

In the desktop view, the onClick button requires two clicks to trigger the onClick function, while in the mobile view, it only takes one click as expected

Here are the topics I want to display as buttons: const paperTopics = [ "Teaching Aptitude", "Research Aptitude", "Comprehension", "Communication", "Mathematical Reasoning and Aptitude", ...

I'm having trouble accessing the outcome from within the function

Having trouble getting the result to return inside a function for my basic rock paper scissors game. I've tried everything, including console logging the compare and putting it inside a variable. Strange enough, console.log(compare) is returning und ...

Step-by-step guide to start an AngularJs application using TypeScript

I have developed an AngularJS App using TypeScript The main app where I initialize the App: module MainApp { export class App { public static Module : ng.IModule = angular.module("mainApp", []) } } And my controller: module MainApp { exp ...

How can I import tamplateData into my JavaScript files in Docpad?

Looking for a DocPad plugin that can preprocess JS files and utilize templateData variables and helpers to access configuration values. While experimenting with Hogan, I managed to retrieve the variables but encountered difficulty in invoking the helpers. ...

Webpack is throwing an error due to the Vue component type being labeled as "any"

When using ts 4.2.4 and Vue3, I encountered a strange error while building my vue project: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a2a7aeaaededb3a2a0a083f3edf2edf3">[email protected]</a> build > v ...

Utilizing Node and Express to promptly respond to the user before resuming the program's

I am accustomed to receiving a user's request, handling it, and providing the outcome in response. However, I am faced with an API endpoint that requires about 10 tasks to be completed across various databases, logging, emailing, etc. All of these ta ...

Load the page's content gradually, without needing to wait for all the content to be fully loaded

I am facing an issue with a webpage that displays 10 different items, each of which has a slow loading time. Currently, the entire page waits for all 10 items to fully load before displaying anything. I am interested in finding out if it is feasible to sh ...

Click the button on your mobile device to open the already installed Android app

After creating a small Android app using jQuery Mobile, I incorporated a button to open another native Android app. Is it feasible for the jQuery Mobile app button to load/open an already installed and functioning native Android app upon click? I would gr ...

Trouble with parsing JSON data in JQuery getJson callback

Recently, I've encountered a strange issue with using jQuery for JSON. Even though the server is responding correctly to the request, I'm having trouble extracting the data from the JSON response. The server is ASP.MVC and is serializing using J ...

Ways to verify if PHP associative arrays are the same, without considering the order of the keys?

Consider having two complex nested arrays in PHP, like the ones below: $c = array( "u" => array(3, 2, 1), "v" => array("w" => "hello", "x" => "world") ); $d = array( "v" => array("x" => "world", "w" => "hello"), " ...

Unfortunately, the server experienced a temporary error and was unable to fulfill your request at this time

When testing the Google Speech API for the first time, I followed the example provided in Google's demo and it was successful. { "config": { "encoding":"FLAC", "sample_rate": 16000, "language_code": "en-US" }, "audio": { ...

Utilizing Angular: Filtering Views Based on JSON Data Values

I am struggling to figure out why a basic Angular filter is not working for me in this example. Despite following the recommended format I found online, it does not seem to be functioning properly. Essentially, I just need to display information from the a ...

Develop a sophisticated multi-page application using create-react-app in conjunction with express.js

While I'm comfortable with back-end work, my front-end programming skills have gotten rusty. I used to work a lot with React, but it's been over a year since I last touched it. Recently, I started a project that requires me to refresh my knowledg ...

Using React to trigger a child component's function upon clicking a tab

I need assistance with creating a React app that includes two tabs (Tab1, Tab2). When Tab2 is clicked, I want a message to appear in the console saying 'Function A is called'. Unfortunately, the code I have currently does not display the message ...

Analyzing various field data collectively

Is there a way to use jQuery to compare multiple input field values and trigger an alert message saying 'There are similar values' if any match is found? <input value="111"> //similar <input value="222"> <input value="111"> //s ...

Guide on uploading files with VueJS and Laravel 5.3

I'm currently working on a single-page application using VueJS, Laravel 5.3, and Passport Authentication module. So far, my code is working fine and I can successfully retrieve the selected file names. However, I am unsure how to proceed with sending ...

Error with review score in material-ui for react.js

There is an issue with my code where the ratings from different sets are not behaving independently. When a rating in one set is clicked, only the first set of ratings changes, suggesting that there is a connection between all the sets. The root cause of ...

HTML Date input field not respecting locale settings and defaults to mm/dd/yyyy format

When using an html date input in an ng-repeat scenario, I noticed that it defaults to mm/dd/yyyy even though my computer's regional settings are set to dd/mm/yyyy. <script src="//unpkg.com/angular/angular.js"></script> <body ng-app&g ...

Unchecking a box becomes impossible in Rails and Ajax due to boolean constraints

Even though I've come across several similar questions, I'm still struggling to make mine work correctly. Here's what my code looks like... #app/views/tasks/index.html.erb <%- @tasks.each do |task| %> <div class="task-wrapper"> ...

What is causing the data not to react with the props in this particular scenario?

In addition to the central App.vue component, I have two other components - Rooms.vue and Desks.vue. When a swiper element in the Rooms.vue component is clicked, it triggers the opening of the Desks.vue component and emits the room object to App.vue. This ...