Nuxt.js Data Fetching Hook: Async Data
In this blog, I am discussing the Nuxt.js asyncData hook. For server-side rendering in Nuxt.js need to use specific hooks. This allows your page to render with all of its required data presents.
Nuxt.js has two hooks for asynchronous data loading:
- The fetch hook
- The asyncData hook
Also, Nuxt.js supports traditional Vue patterns for loading data in your client-side app, such as fetching data in a component's mounted() hook.
Some important features of asyncData hook in Nuxt.js:
- asyncData works on both server-side & client-side rendering.
- asyncData is called every time before loading a component.
- You can use only on next pages, not in vue components.
- anyncData is called from the server-side before the component is mounted. That’s why you don’t have access to ’this’ keyword inside asyncData().
- This method receives the context object as the first argument and you can use it to access core nuxt properties such as route, store, params, app, etc.
- The result from asyncData will be merged with data.
Here is the example of nuxt asyncData using @nuxt/axios library:
<template>
<div>
<h1>{{ post.title }}</h1>
<p>{{ post.description }}</p>
</div>
</template>
<script>
export default {
async asyncData({params, $axios }) {
const post = await $http.$get(`https://api.nuxtjs.dev/posts/${params.id}`)
return { post }
}
}
</script>
asyncData hook returned the promise and resolved during the route transition. This means that no "loading placeholder" is visible during client-side transitions but you can use the loading bar can be used to indicate a loading state to the user.
asyncData() on both client-side & server-side:
To test how asyncData() works on both client-side & server-side, please write the bellow code on your Nuxt.js page.
<script>
export default{
asyncData(context){
console.log(context);
}
}
</script>
Server Side Test
Now reload the page on the browser and look inside your terminal(also can check on browser console panel Nuxt SSR Response) on which your Nuxt.js application running. You can see the context object like the below screenshot. That means its works on the server-side.
Client Side Test
You can also check client-side rendering when you come to this page from another Nuxt.js page (The link must be used NuxtLink for linking between pages). Now open your browser dev tools and check the console panel and you see the magic of asyncData().
How you can use Async data in components:
We already know that we can not use anyncData hook inside any component but we can use another way for component.
Make the API call in the asyncData method of the page component and pass the data as props to the sub components. Both Client & Server side rendering will work fine.
Referance: Nuxt.js Official Data Fetch Hook