nuxt.js logo

Leverage the fetch Hook for Client-Side Data Fetching


Nuxt.js introduces a fetch hook in addition to asyncData, which allows you to fetch data on the client side after the component mounts. Unlike asyncData, which is called only on the server-side during SSR and cannot access the component instance, fetch is called on both the server-side and client-side, providing access to the component's instance. This is particularly useful for updating the data on client-side navigation without needing to re-render the entire page.


Step 1: Use the fetch hook to load data that doesn’t need to be rendered immediately with the server-side HTML, such as data for authenticated user sessions or for dynamic parts of your page that change frequently.

export default {
        data() {
          return {
            posts: []
          };
        },
        async fetch() {
          this.posts = await this.$axios.$get('https://api.example.com/posts');
        },
        fetchOnServer: false,  // Only fetches on client-side navigation
        // You can also control when to fetch data with a watchEffect
        watchQuery: ['page'],
      }

Step 2: Nuxt.js automatically provides a fetchState object within your component that includes properties like pending, error, and timestamp. This can be used to show loading indicators or handle errors in your templates.

<template>
  <div>
    <div v-if="fetchState.pending">Loading...</div>
    <div v-if="fetchState.error">Error! {{ fetchState.error.message }}</div>
    <ul v-else>
      <li v-for="post in posts" :key="post.id">{{ post.title }}</li>
    </ul>
  </div>
</template>

Using the fetch hook effectively allows for dynamic client-side data fetching in Nuxt.js applications, making it an excellent choice for data that changes often or requires user interaction to retrieve, thus optimizing both performance and scalability of your app.