I am facing an issue in my Nuxtjs component where the data fetched from an API is nested. When I try to pass this nested data to the head() method for meta tags, it only works one level deep. Why is this happening?
In the code snippet provided, we are assigning the received data to a constant called post in the components data(). For example,
this.post = data.response.results[0];
. When accessing this.post.webTitle
, everything works fine. However, when trying to access this.post.fields.thumbnail
, it throws an error saying that thumbnail is undefined.
export default {
async fetch() {
const { data } = await this.$axios.get(
`api_url`
);
this.post = data.response.results[0];
this.loading = false;
},
data() {
return {
post: {},
};
},
head() {
return {
title: this.post.webTitle ? `${this.post.webTitle.slice(0, 10)}...` : "",
meta: [
{
hid: "description",
name: "description",
content: this.post.webTitle,
},
{ hid: "og-title", property: "og:title", content: this.post.webTitle },
{
hid: "og-image",
property: "og:image",
content: this.post.fields.thumbnail,
},
{ hid: "og-image-width", property: "og:image:width", content: 500 },
{ hid: "og-image-height", property: "og:image:height", content: 300 },
{
hid: "og-image-type",
property: "og:image:type",
content: "image/jpeg",
},
],
};
},
};
It seems to work fine if we separately assign the deeper data, like so:
this.post = data.response.results[0];
this.thumbnail = data.response.results[0].fields.thumbnail;
data() {
return {
post: {},
thumbnail: "",
};
},
Then, we can access this.thumbnail
without any issues. But why do we have to separately assign the "deeper" data for it to be available in the component?
I would appreciate any insights on this matter. Thank you in advance.