The Fetch hook

The fetch hook is for fetching data asynchronously. It is called on server-side when rendering the route, and on client-side when navigating.


Nuxt >= 2.12

Nuxt v2.12 introduces a new hook called fetch which you can use in any of your Vue components. Use fetch every time you need to get asynchronous data. fetch is called on server-side when rendering the route, and on client-side when navigating.

It exposes $fetchState at the component level:

  • $fetchState.pending: Boolean, allows you to display a placeholder when fetch is being called on client-side.
  • $fetchState.error: null or Error, allows you to display an error message
  • $fetchState.timestamp: Integer, is a timestamp of the last fetch, useful for caching with keep-alive

If you want to call the fetch hook from your template use:

  1. <button @click="$fetch">Refresh</button>

or component method:

  1. // from component methods in script section
  2. export default {
  3. methods: {
  4. refresh() {
  5. this.$fetch()
  6. }
  7. }
  8. }

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

Options

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

The Fetch Hook - 图1

For more info on the Fetch Hook checkout the data fetching chapter of our Features book