Data Fetching

In Nuxt we have 2 ways of getting data from an API. We can use the fetch method or the asyncData method.


Nuxt supports traditional Vue patterns for loading data in your client-side app, such as fetching data in a component’s mounted() hook. Universal apps, however, need to use Nuxt-specific hooks to be able to render data during server-side rendering. This allows your page to render with all of its required data present.

Nuxt has two hooks for asynchronous data loading:

  • asyncData. This hook can only be placed on page components. Unlike fetch, this hook does not display a loading placeholder during client-side rendering: instead, this hook blocks route navigation until it is resolved, displaying a page error if it fails.
  • fetch (Nuxt 2.12+). This hook can be placed on any component, and provides shortcuts for rendering loading states (during client-side rendering) and errors.

These hooks can be used with any data fetching library you choose. We recommend using @nuxt/http or @nuxt/axios for making requests to HTTP APIs. More information about these libraries, such as guides for configuring authentication headers, can be found in their respective documentation.

Data Fetching - 图1

If you define fetch or asyncData inside a mixin and also have it defined in a component/page, the mixin function will be overwritten instead of called.

The fetch hook

Data Fetching - 图2

Before Nuxt 2.12, there was a different fetch hook that only worked for page components and didn’t have access to the component instance.If your fetch() accepts a context argument, it will be treated like a legacy fetch hook. This functionality is deprecated, and should be replaced with either asyncData or an anonymous middleware.

fetch is a hook called during server-side rendering after the component instance is created, and on the client when navigating. The fetch hook should return a promise (whether explicitly, or implicitly using async/await) that will be resolved:

  • On the server, before the initial page is rendered
  • On the client, some time after the component is mounted

Data Fetching - 图3

For static hosting, the fetch hook is only called during page generation, and the result is then cached for use on the client. To avoid cache conflicts, it may be necessary to specify a name for your component, or alternatively provide a unique fetchKey implementation.

Usage

Fetching data

Within the fetch hook, you will have access to the component instance via this.

Data Fetching - 图4

Make sure any properties you want to modify have already been declared in data(). Then the data that comes from the fetch can be assigned to these properties.

Changing fetch behavior

fetchOnServer: Boolean or Function (default: true), call fetch() when server-rendering the page

fetchKey: String or Function (defaults to the component scope ID or component name), a key (or a function that produces a unique key) that identifies the result of this component’s fetch (available on Nuxt 2.15+). When hydrating a server-rendered page, this key is used to map the result of the server-side fetch() to the client-side component data. More information available in original PR.

fetchDelay: Integer (default: 200), set the minimum executing time in milliseconds (to avoid quick flashes)

When fetchOnServer is falsy (false or returns false), fetch will be called only on client-side and $fetchState.pending will return true when server-rendering the component.

  1. export default {
  2. data: () => ({
  3. posts: []
  4. }),
  5. async fetch() {
  6. this.posts = await this.$http.$get('https://api.nuxtjs.dev/posts')
  7. },
  8. fetchOnServer: false,
  9. // multiple components can return the same `fetchKey` and Nuxt will track them both separately
  10. fetchKey: 'site-sidebar',
  11. // alternatively, for more control, a function can be passed with access to the component instance
  12. // It will be called in `created` and must not depend on fetched data
  13. fetchKey(getCounter) {
  14. // getCounter is a method that can be called to get the next number in a sequence
  15. // as part of generating a unique fetchKey.
  16. return this.someOtherData + getCounter('sidebar')
  17. }
  18. }

Accessing the fetch state

The fetch hook exposes this.$fetchState at the component level with the following properties:

  • pending is a Boolean that allows you to display a placeholder when fetch is being called on client-side.
  • error is either null or an Error thrown by the fetch hook
  • timestamp is a timestamp of the last fetch, useful for caching with keep-alive

In addition to fetch being called by Nuxt, you can manually call fetch in your component (to e.g. reload its async data) by calling this.$fetch().

components/NuxtMountains.vue

  1. <template>
  2. <div>
  3. <p v-if="$fetchState.pending">Fetching mountains...</p>
  4. <p v-else-if="$fetchState.error">An error occurred :(</p>
  5. <div v-else>
  6. <h1>Nuxt Mountains</h1>
  7. <ul>
  8. <li v-for="mountain of mountains">{{ mountain.title }}</li>
  9. </ul>
  10. <button @click="$fetch">Refresh</button>
  11. </div>
  12. </div>
  13. </template>
  14. <script>
  15. export default {
  16. data() {
  17. return {
  18. mountains: []
  19. }
  20. },
  21. async fetch() {
  22. this.mountains = await fetch(
  23. 'https://api.nuxtjs.dev/mountains'
  24. ).then(res => res.json())
  25. }
  26. }
  27. </script>

Data Fetching - 图5

You can access the Nuxt context within the fetch hook using this.$nuxt.context.

Listening to query string changes

The fetch hook is not called on query string changes by default. To watch for query changes you can add a watcher on $route.query and call $fetch:

  1. export default {
  2. watch: {
  3. '$route.query': '$fetch'
  4. },
  5. async fetch() {
  6. // Called also on query changes
  7. }
  8. }

Caching

You can use keep-alive directive in <nuxt/> and <nuxt-child/> component to save fetch calls on pages you already visited:

layouts/default.vue

  1. <template>
  2. <nuxt keep-alive />
  3. </template>

You can also specify the props passed to <keep-alive> by passing a prop keep-alive-props to the <nuxt> component.

layouts/default.vue

  1. <nuxt keep-alive :keep-alive-props="{ max: 10 }" />

Keeps only 10 page components in memory.

Error handling

Data Fetching - 图6

If there is an error when fetching data, the normal Nuxt error page won’t be loaded - and you should not use the Nuxt redirect or error methods within fetch(). Instead, you will need to handle it within your component using $fetchState.error.

We can check $fetchState.error and show an error message if there is an error fetching the data.

components/MountainsList.vue

  1. <template>
  2. <div>
  3. <p v-if="$fetchState.pending">Loading....</p>
  4. <p v-else-if="$fetchState.error">Error while fetching mountains</p>
  5. <ul v-else>
  6. <li v-for="(mountain, index) in mountains" :key="index">
  7. {{ mountain.title }}
  8. </li>
  9. </ul>
  10. </div>
  11. </template>
  12. <script>
  13. export default {
  14. data() {
  15. return {
  16. mountains: []
  17. }
  18. },
  19. async fetch() {
  20. this.mountains = await fetch(
  21. 'https://api.nuxtjs.dev/mountains'
  22. ).then(res => res.json())
  23. }
  24. }
  25. </script>

Using activated hook

Nuxt will directly fill this.$fetchState.timestamp (timestamp) of the last fetch call (ssr included). You can use this property combined with activated hook to add a 30 seconds cache to fetch:

pages/posts/_id.vue

  1. <template> ... </template>
  2. <script>
  3. export default {
  4. data() {
  5. return {
  6. posts: []
  7. }
  8. },
  9. activated() {
  10. // Call fetch again if last fetch more than 30 sec ago
  11. if (this.$fetchState.timestamp <= Date.now() - 30000) {
  12. this.$fetch()
  13. }
  14. },
  15. async fetch() {
  16. this.posts = await fetch('https://api.nuxtjs.dev/posts').then(res =>
  17. res.json()
  18. )
  19. }
  20. }
  21. </script>

The navigation to the same page will not call fetch if last fetch call was before 30 sec ago.

Async Data

Data Fetching - 图7

asyncData is only available for pages and you don’t have access to this inside the hook.

asyncData is another hook for universal data fetching. Unlike fetch, which requires you to set properties on the component instance (or dispatch Vuex actions) to save your async state, asyncData simply merges its return value into your component’s local state. Here’s an example using the @nuxt/http library:

pages/posts/_id.vue

  1. <template>
  2. <div>
  3. <h1>{{ post.title }}</h1>
  4. <p>{{ post.description }}</p>
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. async asyncData({ params, $http }) {
  10. const post = await $http.$get(`https://api.nuxtjs.dev/posts/${params.id}`)
  11. return { post }
  12. }
  13. }
  14. </script>

Unlike fetch, the promise returned by the asyncData hook is resolved during route transition. This means that no “loading placeholder” is visible during client-side transitions (although the loading bar can be used to indicate a loading state to the user). Nuxt will instead wait for the asyncData hook to be finished before navigating to the next page or display the error page).

This hook can only be used for page-level components. Unlike fetch, asyncData cannot access the component instance (this). Instead, it receives the context as its argument. You can use it to fetch some data and Nuxt will automatically shallow merge the returned object with the component data.

In the upcoming examples, we are using @nuxt/http which we recommend for fetching data from an API.

Async data in components?

Because components do not have an asyncData method, you cannot directly fetch async data server side within a component. In order to get around this limitation you have three basic options:

  1. Use the new fetch hook that is available in Nuxt 2.12 and later versions.
  2. Make the API call in the mounted hook and set data properties when loaded. Downside: Won’t work for server side rendering.
  3. Make the API call in the asyncData method of the page component and pass the data as props to the sub components. Server rendering will work fine. Downside: the asyncData of the page might be less readable because it’s loading the data for other components.

Listening to query changes

The asyncData method is not called on query string changes by default. If you want to change this behavior, for example when building a pagination component, you can set up parameters that should be listened to with the watchQuery property of your page component.

Data Fetching - 图8

Learn more about the watchQuery property and see the list of available keys in context.