bazass55
bazass55

Reputation: 1

Axios Get Request Not Working with Json Array Object

I'm trying to fetch second [1] item's title from an object array in JSON:

{
    "@attributes": {
        "version": "2.0"
    },
    "channel": {
        "title": "Rust News",
        "description": "The latest news posts from Rust",
        "lastBuildDate": "Thu, 07 Jul 2022 07:00:00 Z",
        "item": [
            {
                "guid": "https:\/\/rust.facepunch.com\/news\/july-2022-update\/",
                "link": "https:\/\/rust.facepunch.com\/news\/july-2022-update\/",
                "title": "July Update",
                "description": "<img src=\"https:\/\/files.facepunch.com\/paddy\/20220705\/july_2022_header.jpg\"><br\/>Combat balance, faster load times, chat filter and much more!\u00a0\u00a0",
                "pubDate": "Thu, 07 Jul 2022 07:00:00 Z"
            },
            {
                "guid": "https:\/\/rust.facepunch.com\/news\/community-update-243\/",
                "link": "https:\/\/rust.facepunch.com\/news\/community-update-243\/",
                "title": "Community Update 243",
                "description": "<img src=\"https:\/\/files.facepunch.com\/errn\/1b1311b1\/FTTfqglWQAMxkzD.jpg\"><br\/>Custom desk mats, Mars monuments, thoughtful poetry, and more!",
                "pubDate": "Wed, 15 Jun 2022 12:00:00 Z"
            }
...

Here is the axios code:

  mounted() {
    this.axios.get("./api/feedRust.php").then(response => {
        this.items = response.data.channel;
    });
  }

Everything works as expected when tusing response.data.channel, however unable to fetch any object from item array due to this error:

Cannot read properties of undefined (reading '1')

HTML/Vuejs code:

<div>{{items.item[1].title}}<div>

What could be wrong here?

Upvotes: 0

Views: 142

Answers (1)

Riyaz Khan
Riyaz Khan

Reputation: 3228

You need to make sure you defined data with the property, because while fetching the response data, it will try to access the items.item, which may not exists with the index.

Add the conditional statement.

Like this:

<div v-if="items.item && items.item.length > 1">{{items.item[1].title}}<div>

Upvotes: 2

Related Questions