Retrieve the header tag from API using Nuxt

I am trying to dynamically set OG:Tags using an 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,
        }
      ]
    };
  });

However, despite printing correctly in the console, the tags do not show up when testing on production.

Answer №1

It is recommended to make Axios requests (and any other asynchronous calls) within the asyncData method. asyncData will seamlessly integrate its returned value into your component's internal state, allowing you to access this data using this.

Keep in mind that asyncData is specifically designed for components located in the pages folder.

Here is an example utilizing 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some strategies for stopping a form from redirecting me while utilizing ReactJS and ExpressJS?

Recently, I created a form that redirects to the route /repair upon submission with an action of /repair. However, I would prefer to keep it as a Single Page Application (SPA) where after submitting the form, the fields are cleared, and a simple message l ...

The functionality of the Bootstrap4 accordion is not functioning according to my expectations

My goal is to create a unique e-commerce checkout page design. Each panel would be opened sequentially, with the next panel unfreezing when the action button of the current panel is clicked. However, I seem to be making a mistake as it is not working as in ...

How to Invoke JavaScript Functions within jQuery Functions?

I'm working on a jQuery function that involves dynamically loading images and checking their width. I have two JavaScript functions, func1() and func2(), that I want to call from within the jQuery function in order to check the width of each image. T ...

Babel had a SyntaxError in test.jsx file at line 3, position 11 with an Unexpected token

Having trouble converting JSX to JS with Babel? If you're seeing an error like the one below, don't worry - we can help you fix it: The example code in test.jsx is causing a SyntaxError when transformed using babel test.jsx: SyntaxError: test ...

Displaying the loading image only on the first result within a while loop

When a submit button is clicked on any result, the loading image below the button displays only for the first result in the while loop. For example, if I click the submit button on the first result, the loading image shows below it. However, when I click t ...

Error in code - message gets sent immediately instead of waiting for timeout to occur

There seems to be an issue with the code where the message is sent instantly instead of waiting for the specified timeout duration. Based on the code, it should wait for the time mentioned in the message. I'm puzzled as to why it's not functioni ...

Obtaining a Variable Element through Selector

When working with Puppeteer, I am faced with the challenge of clicking on a web button that has a dynamic id like: #product-6852370-Size. Typically, I would use the following code: page.click('#product-6852370-Size'); However, the number withi ...

Ways to create a class method to increase a counter?

Can someone help me figure out how to create a custom function or class from the code below? I want to be able to import this module in order to easily increment a count whenever an event occurs in my application. I'm tired of having to manually inpu ...

Is it possible to utilize Vue.js' v-if directive to validate if a certain value is present within an array

In my form, I have a checkbox and I want to be able to use v-if directly to display or hide sections based on the selected checkbox values. Can this be done using v-if, or do I need to use watch:? ...

Merging two arrays that have identical structures

I am working on a new feature that involves extracting blacklist terms from a JSON file using a service. @Injectable() export class BlacklistService { private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist'; private readonly blackl ...

React/Javascript - Executing Function returns prematurely

I have been working on a function that takes an object and iterates through it to create a search query. However, the issue I'm facing is that the function returns before I finish looping through the object: export default function buildQuery(query) ...

How can I dynamically change a key in an object and replace it with a custom name while also updating its value?

Transform this =>>>>> {1: "Baroque", 2: "Glitch Pop ", 3: "Nu Jazz", 4: "Drumfunk", 5: "Bitpop", 6: "Latin Pop", 7: "Carnatic"} into this ==>>>> [{id: 1 name ...

Using JavaScript to implement CSS3 with multiple background images

Is there a way to programmatically define multiple background images in CSS3 using JavaScript? While the common approach would be: var element = document.createElement( 'div' ); element.style.backgroundImage = "url('a.png') 0 100%, ur ...

Using a constructor function in a for loop

Currently, I am learning how to build a Blackjack game with Javascript on Codecademy. I'm struggling to figure out what code to write inside the for-loop. The task at hand is to create a "score" method within the Hand constructor. This method should ...

Having difficulty displaying elements from two arrays at particular intervals

I am currently working with two arrays that have the same number of items in each. My goal is to print these items in intervals within the console. The desired output would look something like this: 1 Bruce Wayne 45 Then, after a one-second interval, it s ...

Execute the gulp module on the source files

Recently, I've been delving into the world of gulp and trying to enhance the readability of my js source files. I have a task in place (which executes successfully) that utilizes 'gulp-beautify' to beautify the js files: gulp.task('js& ...

Progress Bar Countdown Timer

I have made some progress on my project so far: http://jsfiddle.net/BgEtE/ My goal is to achieve a design similar to this: I am in need of a progress bar like the one displayed on that site, as well as the ability to show the days remaining. Additionally ...

Troubleshooting problem with iPhone X responsiveness

Struggling with responsive issues on iPhone X. Issue is only appearing on actual device. Any tips for fixing this? I'm facing an issue where the website looks good and responsive on all devices in Chrome's responsive view. But when I access it th ...

Adjust the height of images to be consistent

I'm currently working on creating a grid layout with 4 images in a row using DaisyUI card component. However, I've run into an issue where there is white space at the bottom of some images due to varying image heights. Is there a solution that wo ...

I'm feeling a bit lost with this JSON example - specifically with JSON.parse, JSON.stringify, as well as localStorage.setItem

As a beginner in learning JSON, I find that W3schools does not provide clear explanations of what each line of code does. While I can interpret some parts, there are sections that still remain unclear to me. // Data storage process: 1. myObj = {name: "Jo ...