Nuxt (>= 2.12) Fetch

Jun 12, 2020

The easiest way to fetch data using Nuxt is via asyncData, as a lot of things is handled for you (loading animation, data merging, state management, etc) and it just works.

If you need more control, you should use fetch.

  • Render UI based on $fetchState (loading, error and success)
  • Have access to this / page component.
  • Ability to disable fetchOnServer forcing fetch to be called on client side only
  • Ability to call this.$fetch()
  • Enable fetch cache

Code

<template>  <div>    <div v-if="$fetchState.pending">Loading ...</div>    <div v-else-if="$fetchState.error">Error: {{ $fetchState.error.message }}</div>    <div>      {{ title }}    </div>  </div></template><script>export default {  async fetch() {    // const HOST = 'http://localhost:8080' // required for server-side fetch    // const url = new URL(`/data/test.json`, HOST)    const url = 'https://jsonplaceholder.typicode.com/posts/1'    // alternatvely, you could use $axios or $http    const res = await fetch(url)    const data = await res.json()    this.title = data.title  },  data() {    return {      title: null    }  },}</script>

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.