Kos-Mos
Kos-Mos

Reputation: 707

Is it possible to use nuxt fetch() and set the values in head()?

The problem is that head() seems to be executed before async fetch(), which causes errors when trying to insert page's metadata and title. I KNOW asyncData exists, but the fact that it blocks page loading at a route transition level makes it provide such a HORRIBLE user experience (in a mobile device with bad connection, page transition can stay blocked for seconds) and reminds of old PHP rendered websites, not a modern SPA. Nuxt fetch() in the other hand, while still server side rendering the page, exposes $fetchState.pending and makes possible to exhibit an instant page transition showing the page skeleton, for example (consequently making the user experience better). The only problem i am having is this one with head() data. Is this problem solvable or just one unsolvable drawback of using fetch() instead of asyncData()?

Important Note: I am referring to Nuxt's new fetch method, not the legacy one.

example code that doesn't work:

data() {
  return {
    car: null,
  }
},
async fetch() {
  this.car = await this.$axios.$get('/cars/' + this.$route.params.id)
},

head() {
    return {
      title: this.car.name,
    }
  },

Upvotes: 1

Views: 1404

Answers (1)

kissu
kissu

Reputation: 46604

My colleague did a talk a few weeks ago, speaking about SEO in general, here is related section: https://youtu.be/W9camkXNjkw?t=920

Looking at all my given answers regarding SEO and also Github issues, all examples are using asyncData or some static approach.
When you think about it, I'm not sure how you could generate something on SSR, while being totally dynamic + non-blocking.

Either you know it ahead of time and can generate the OG tags, or you don't if it's totally volatile.

Upvotes: 1

Related Questions