1

When getting json data from API,Im unable to access nested ppts.

My Vue component

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>
`}

This Doesnt work but when I change {{ activeUser.address.street }} to {{ activeUser.address }} it starts working.Note the users object from jsonplaceholder website contains street ppt as well.What am I missing?

1
  • activeUser is an empty string by default so you access activeUser.address it is undefined and if you use activeUser.address.street it gives an error. Commented Dec 5, 2018 at 5:42

1 Answer 1

3

activeUser is an empty string by default so you access activeUser.address it is undefined and if you use activeUser.address.street it gives an error For resolving this issue you can use

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

instead of simple

<p>{{ activeUser.address.street }}</p>
Sign up to request clarification or add additional context in comments.

1 Comment

Works now thanks.Will mark this as most useful in some time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.