Changing the metadata in the head section of a Nuxt.js application based on dynamic data fetched

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.

Answer №1

The reason for this issue is likely due to the fact that the head function is executed before the fetch function has a chance to return the data. Since this.post is defined as an object, accessing this.post.webTitle would result in it being undefined. However, attempting to access this.post.fields.thumbnail is essentially trying to access the property thumbnail of an undefined value, which is not valid.

If you were to modify the data method like so:

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

I believe this adjustment should resolve the issue.

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

JavaScript code to shift a box beyond the boundaries of a grid

I have a yellow square within a grid. Upon clicking the 'UP' button, the yellow square moves up by one box. How can I ensure that the square stops at the edge of the grid and does not move out? let moveCounter = 0; var grid = document.getElem ...

Tips on adjusting the rendering sequence of components in vueJs?

Is it possible to reorder child components based on data from an API in the parent component? Here is an example: Parent component: <div v-if="data"> <Component_1 /> <Component_2 /> <Component_3 /> <Com ...

Looping through multi-dimensional arrays in JavaScript is a necessary task for accessing

I have been trying to figure out how to create a multidimensional array like this: [[A1, B1, C1....],[A2, B2, C2....]]; let grid = [ [] ]; let letters = "abcdefghij".toUpperCase(); // Generating the Grid const generateGrid = (size) => { let row ...

What methods can I use to minimize the frequency of the blue box appearing around text?

I successfully developed code that enables user interaction with text, triggering the opening of a modal box when clicked. In this modal box, the text turns red upon clicking, indicating activation of a checkbox. However, I notice that every time I intera ...

Can the load API in jQuery be utilized to load fragments using a class selector instead of an id?

I've been working on enhancing a website's dashboard by incorporating more widgets onto the page. Interestingly, these widgets are already present on another page within the same domain. After some research, I discovered that utilizing the load A ...

What criteria should I consider when selecting a JavaScript dependency framework?

When it comes to installing dependencies, how do I determine whether to use NPM or Bower? For example, what distinguishes npm install requirejs --save-dev from bower install requirejs --save-dev? Is there a recommended method, or any guidelines for makin ...

Issue Alert: DateField.getValue() function does not exist

Whenever I try to retrieve the value using DateField.getValue(), (this.toDate.getValue()=="" && this.toDate.getValue()=="") An error is thrown with the message: Error Msg : DateField.getValue() is not a function This occurs in the following ...

Sliding through transitions in VueJS

I'm struggling with a form that has three steps where each step should transition from side to side on click of 'prev'/'next'. The issue I'm facing is that the transitions aren't being applied correctly after a direction ...

Is it possible to prevent the fade out of the image when hovering over the text after hovering over the div or image, causing the text to fade in?

Using React and CSS. I have set up my application to display a faded image on hover, with text that fades in over it. However, I am facing an issue where touching the text with my cursor removes the fade effect. Does anyone have a solution for preventing ...

Issues with implementing Dark mode in TailwindCSS with Nuxt.js

After spending a couple of days on this, I'm still struggling to get the dark mode working with Tailwind CSS in Nuxt.js. It seems like there might be an issue with the CSS setup rather than the TypeScript side, especially since I have a toggle that sw ...

Tips for preventing the unmounting of child components while utilizing JSX's map function

This is a condensed version of a question I previously asked. Hopefully, it's clearer and more comprehensible. Here is a simple application with 3 input fields that accept numbers (disregard the ability to enter non-numbers). The app calculates the s ...

"Uncaught ReferenceError: $ is not defined - $function()" error in JavaScript/jQuery

When attempting to execute a JavaScript/jQuery function, an error is encountered when using Firebug: $ is not defined $(function()". The issue arises from the placement of the JavaScript code within a file named core.js that is referenced by index.php. W ...

Retrieve text from a dropdown menu while excluding any numerical values with the help of jQuery

I am currently implementing a Bootstrap dropdown menu along with jQuery to update the default <span class="selected">All</span> with the text of the selected item by the user. However, my objective is to display only the text of the selected it ...

How to generate a hyperlink in JQGrid

Trying to create clickable links in all cells of a column within my JQgrid. These links should call a javascript function passing the cell value for server-side queries. After researching on html link column in jqGrid, I have attempted the following: colM ...

Is there a bug in NodeJS that causes an error when a return statement is used with a line feed before the string to be returned?

I am attempting to call a function from a module in order to generate an HTML string. When the function is written with a line feed (LF) between the return statement and the string declaration as shown below, the return value becomes "undefined"... export ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

Guide on creating a respond_to using AJAX in Rails 3?

I am encountering an issue with my form and AJAX. The form resides in the FirstsController, but I need it to be sent to the SecondsController. After successfully sending the form and saving the data, I attempt to replace the form with text using the follow ...

The clarity and completeness of images on canvas are lacking

I've experimented with numerous examples found on the internet, but none of them seem to be effective. My goal is to display a full image on a canvas without it being zoomed in and losing quality. In addition, I attempted to rotate images (from stand ...

Unable to define headers within a request when using AngularJS

My application consists of two parts - an Angular frontend and a Rails server. Since they are on different domains, requests do not work by default. I have tried various solutions, including adjusting the stack, but nothing seems to work for me. Below is ...

The acceleration of the ThreeJS scene intensifies with each passing moment

My friend and I have been collaborating on a university assignment - creating a basic Pacman clone using ThreeJS (which is a requirement). From the start, we've encountered a persistent issue. As our scene continues to run, it progressively speeds up ...