DEV Community

loading...

Refactoring API Calls in Nuxt

cwraytech profile image Christopher Wray Updated on ・1 min read

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

Discussion (0)

pic
Editor guide