Home » vue » nuxtjs head meta tag dynamic modify on fetch()

nuxtjs head meta tag dynamic modify on fetch()

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have this component in Nuxtjs, which renders content fetched using fetch method from API. API gives back data as nested object. When I pass this data to head() method for meta tags it works only one level deep, but not with nested data. Why is that?

In this code we assign recived data to const post in components data() this.post = data.response.results[0];. Then when using this.post.webTitle its fine, but when using this.post.fields.thumbnail an error occurs stating 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",
        },
      ],
    };
  },
};

when separately assign

this.post = data.response.results[0];
this.thumbnail = data.response.results[0].fields.thumbnail;

data() {
    return {
      post: {},
      thumbnail: "",
    };
  },

then its working ok, I I can use:

this.thumbnail

I don’t understand why it’s not working in the first way? Why I have to separately assign “deeper” data to make it available to component?

Thank you for help in advance

Answers:

This is most likely because head is run before fetch is able to return data. As this.post is defined as an object, it is legal to access this.post.webTitle as it would just be undefined. But this.post.fields.thumbnail is trying to access thumbnail of undefined, which is illegal.

If you change data to:

data() {
    return {
      post: {
          fields: {
              thumbnail: ""
          }
      },
    };
  },

I suspect it would work