DEV Community

Christopher Wray
Christopher Wray

Posted on • Edited on

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

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 :)