Jirakit Paitoonnaramit
Jirakit Paitoonnaramit

Reputation: 167

Nuxt get Heading tag from API

I need to set OG:Tag from API

head() {
this.$axios
  .get(`............`)
  .then((response) => {
    this.og_title = response.data.message.course.course_name;
    this.og_description = response.data.message.course.description;
    this.og_image = response.data.message.course.img_url;

    console.log(this.og_title);
    return {
      title: this.title,
      meta: [
        {
          property: "og:title",
          content: this.og_title,
        },
        {
          property: "og:description",
          content: this.og_description,
        },
        {
          property: "og:image",
          content: this.og_image,
        },
      ],
    };
  });

and it does not work But in console it already print correctly total but when test on production it does not have any tag.

Upvotes: 0

Views: 230

Answers (1)

Andrii Goshovskiy
Andrii Goshovskiy

Reputation: 26

You should perform Axios request (and any other async calls) in asyncData method. asyncData simply merges its return value into your component's local state, so you can access that data with this.

Please note, asyncData only works in pages folder components.

Here's an example using the @nuxt/http library:

<script>
  export default {
    async asyncData({ params, $http }) {
      const post = await $http.$get(`https://api.nuxtjs.dev/posts/${params.id}`)
      return { post }
    },
    head() {
      return {
        title: this.post.title,
        meta: [
          {
            property: "og:title",
            content: this.post.title,
          },
          {
            property: "og:description",
            content: this.post.description,
          },
          {
            property: "og:image",
            content: this.post.image,
          },
        ],
      };
    }
  }
</script>

Upvotes: 1

Related Questions