Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Traversing an object after fetching it in Vue

I’m fetching some data like so:

Vue.createApp({
data(){
    object: {},
},
...
mounted() {
    fetch("{SERVER_URL}/someurl.php?=getObject")
                    .then((response) => response.json())
                    .then((data) => {
                        this.object = data;
    }
...
}

Then, in the html I do the following

<div>{{object.parent.child}}</div>

Which returns

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Uncaught TypeError: Cannot read properties of undefined (reading 'child')

While {{translations.parent}} correctly returns the parent object.

This is what the object looks like;

{
    "parent": {
        "child": "value",
        ...
    },
    ...
}

How can I correctly retrieve the childvalue?

>Solution :

Before you fetch your data from server, your object doesn’t have the parent attribute / key, but you are trying to access it. So, improve your code this way:

<div>{{object.parent?.child}}</div>

or this way, if you want to have more backwards compatible code:

<div>{{object.parent && object.parent.child}}</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading