DEV Community

Christopher Wray
Christopher Wray

Posted on • Edited on

3 1

Refactoring API Calls in Nuxt

Today when I wanted to build out the head attributes in Nuxt, I realized that when using asyncData() to pull in API data, you do not have access to this.

That was a problem when I needed to use the data pulled from the API in my head tag, so I went and looked back at the docs some more.

It looks like the best way to fetch data from an API in Nuxt is the fetch() hook!

Makes sense.

After I refactored, my script tag looks a lot cleaner and page changes are much faster with the keep-alive attribute set on my component in the default layout.

This is what the Home page component script tag looks like now:

export default {
  data () {
    return{
      home: {},
      posts: [],
      projects: []
    }
  },
  async fetch() {
    this.home = await this.$axios.$get("/home-page")

    this.posts = await this.$axios.$get("/posts?_limit=4")

    this.projects = await this.$axios.$get("/projects?_limit=2")
  },
   head() {
      return {
        title: this.home.title,
        meta: [
          // hid is used as unique identifier. Do not use `vmid` for it as it will not work
          {
            hid: 'description',
            name: 'description',
            content: this.home.meta_description
          }
        ]
      }
    },
    fetchOnServer: true
}

Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (1)

Collapse
 
megcgo profile image
Marcio Cardoso

Hi Christopher,

(I know you probably already know this at this time)

You cannot use "this" on the asyncData because asyncData merges the data with data() object. So instead of creating the home object in data(), you can create it on the asyncData and you can use it on the meta :)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more