Fetch Hook vs Async Data in Nuxt.js

Yahya Gok
2 min readJul 10, 2021

Nuxt.js gives us two different way to fetch data from an Api, one is Fetch hook, the other one is Async Data.

1-) Fetch Hook

fetch hook allows us to fetch data from any component. We could be able to use fetch hook with any component we want.

in the original document, it shows how to fetch data in the below.


<script>
export default {
data() {
return {
mountains: []
}
},
async fetch() {
this.mountains = await fetch(
'https://api.nuxtjs.dev/mountains'
).then(res => res.json())
}
}
</script>

Let’s adjust this to in our example;

I have Reviews component and I could be able to use data as shown in documents from line 16 to 25.(picture 1)

First we have data() function and this function holds an array of our api’s data that we want to fetch. Then, getting data with this like the below;

async fetch(){
this.reviewrs = await fetch ('http://randomuser.me/api/?
results=5').then(res => res.json() );
}

After getting reviewers array full with fetching, we could be able to use it in our component on line 6 below picture.

picture 1

2-) Async Data

Async Data can only fetch data on page level, this data types require to be in page folder in our nuxt.js app.

As you can see in below picture, in pages folder index.vue file has async created() function on line 44, after doing the fetch with line 51 and 52 , we get all the data to products array on line 39.

Resources

--

--