Drilling down an object throws "Cannot read property of undefined" [REACT]

in the object below

data.author.name
or
data.img[0].url

throws name is undefined, or 0 is undefined
or
same as some nested obeject pls how do i resolve this…?

{
    "img": [
        {
            "_id": "60a3eeef1af8e4244ce2b035",
            "name": "knots of love.jpg",
            "alternativeText": "",
            "caption": "",
            "hash": "knots_of_love_7814a03a3f",
            "ext": ".jpg",
            "mime": "image/jpeg",
            "size": 5.76,
            "width": 124,
            "height": 198,
            "url": "/uploads/knots_of_love_7814a03a3f.jpg",
            "formats": {
                "thumbnail": {
                    "name": "thumbnail_knots of love.jpg",
                    "hash": "thumbnail_knots_of_love_7814a03a3f",
                    "ext": ".jpg",
                    "mime": "image/jpeg",
                    "width": 98,
                    "height": 156,
                    "size": 4.18,
                    "path": null,
                    "url": "/uploads/thumbnail_knots_of_love_7814a03a3f.jpg"
                }
            },
            "provider": "local",
            "related": [
                "60a3ef061af8e4244ce2b036"
            ],
            "createdAt": "2021-05-18T16:44:31.322Z",
            "updatedAt": "2021-05-18T16:44:54.842Z",
            "__v": 0,
            "id": "60a3eeef1af8e4244ce2b035"
        }
    ],
    "_id": "60a3ef061af8e4244ce2b036",
    "pageCount": 500,
    "title": "Knots of love",
    "description": "True Love knows no bound",
    "datePublished": "2019-11-01",
    "createdAt": "2021-05-18T16:44:54.832Z",
    "updatedAt": "2021-05-18T16:45:11.295Z",
    "__v": 0,
    "author": {
        "_id": "60a3e3591af8e4244ce2b031",
        "name": "Robert Gold",
        "createdAt": "2021-05-18T15:55:05.985Z",
        "updatedAt": "2021-05-18T15:55:05.997Z",
        "__v": 0,
        "id": "60a3e3591af8e4244ce2b031"
    },
    "id": "60a3ef061af8e4244ce2b036"
}
1 Like

I know it’s rather an old question, but if anyone stumbles upon it, I want to share my case.

I got the same error just because I accessed data incorrectly. I fetched the endpoint based on a slug, with query param like this:

const post = await fetcher(`${process.env.NEXT_PUBLIC_HCMS_API_URL}/posts?slug=${params.slug}`)

When you fetch Strapi API with a slug, instead of an object it returns an array with that data object inside. While in the previous project I fetched API through id, like this:

const post = await fetcher(`${process.env.NEXT_PUBLIC_HCMS_API_URL}/posts/${params.id}`)

But this time I wanted that my post urls were clear with slugified title and I fetched the data by slug. So, the right approach would be something like this: data[0].author.name, data[0].img[0].url

1 Like