Using asyncData in Nuxt 3
Part 4 of 9 in Upgrading Nuxt 2 to Nuxt 3Nuxt 3 has a slightly different syntax for using asyncData()
than Nuxt 2. In this short tutorial, we will touch on a few of the differences we ran across when migrating ROAST from Nuxt 2 to Nuxt 3. There are a lot of updated changes when it comes to data fetching, so I’d recommend checking out the Nuxt 3 docs for further insight!
In ROAST we used asyncData for a lot of our initial data loading. In Nuxt 3 you can continue to use asyncData, it’s just been adapted for Vue 3.
Individual asyncData()
request
The biggest difference when setting up async data from Nuxt 2 to Nuxt 3 is migrating to the Vue 3 composition API. In Nuxt 2, asyncData
worked with the options API where Nuxt 3 provides a super helpful composable (useAsyncData()
) that performs the same function.
When loading the statistics in the footer of ROAST, we have a simple asyncData()
method that loads the stats. In Nuxt 2, the request looks like:
async asyncData({ $http }) {
const stats = await $http.$get(`/api/v1/stats`)
return { stats }
}
We make a request to our endpoint, and return the stats
variable that we can use within our component.
In Nuxt 3, the same setup request looks like:
const { data:stats } = await useAsyncData( 'stats', () => $fetch( config.API_BASE_URL+'/stats') );
Just a heads up! You will need to put this in your setup()
function or within <script setup>
to use the composable! The main difference between the two requests is the composable useAsyncData()
. The request calls the $fetch
plugin provided by Nuxt to perform the request.
When returned, we decouple the data
from the response, and give it the name of stats
. This way we can use the stats
variable in our component and in our template. Next up, let’s take a look at making two simultaneous requests.
Simultaneous asyncData()
requests
An example of where we used asyncData
is on the individual cafes page to load up the cafe
and the company
resources from our API.
In Nuxt 2, we would call two endpoints that returned promises and our request looked like:
async asyncData ( { $http, params, error } ) {
try{
const [ cafe, company ] = await Promise.all([
$http.$get(`http://api.roastandbrew.coffee/api/v1/companies/${params.company}/cafes/${params.cafe}`),
$http.$get(`http://api.roastandbrew.coffee/api/v1/companies/${params.company}/cafes/${params.cafe}`)
]);
async asyncData ( { app, params, error } ) {
try{
const [ cafe, company ] = await Promise.all([
$http.$get(`https://api.roastandbrew.coffee/api/v1/companies/${params.company}/cafes/${params.cafe}`),
$http.$get(`https://api.roastandbrew.coffee/api/v1/companies/${params.company}`)
]);
return {
cafe: cafe,
company: company
}
} catch ( e ){
error( {
statusCode: 404, message: ''
});
}
},
Luckily, you can do the same thing with Nuxt 3 as long as you apply a few updates. Our Nuxt 3 request looks like:
export default defineComponent({
async setup() {
const config = useRuntimeConfig();
const route = useRoute();
const [{ data: company }, { data: cafe }] = await Promise.all([
useFetch(config.API_BASE_URL+'/companies/'+route.params.company),
useFetch(config.API_BASE_URL+'/companies/'+route.params.company+'/cafes/'+route.params.cafe)
])
return {
company,
cafe
}
}
})
First, since Nuxt 3 runs on Vue 3, it’s recommended to use the Composition API. Because of that, we need to make the setup()
method asynchronous. If you are doing async setup, that means you can’t use the <script setup>
syntax. Just a heads up!
Next, will also need to use the useFetch()
composable instead of the $http
plugin. The useFetch()
composable wraps the ohmyfetch API to make API requests a breeze!
Finally, you will have to import the dynamic route parameters using useRoute()
. We will talk more about dynamic route parameters in the next tutorial, just bringing awareness here!
If you want to skip ahead and learn a little bit more about data fetching with Nuxt 3, check out Advanced Data Fetching with Nuxt 3!
Conclusion
There are a few syntax changes, but overall the functionality is very similar. Let me know if you are running into issues! Feel free to reach out on Twitter or on our community forum.
If you are interested in seeing the entire Nuxt 3 codebase for ROAST, we have a book available! In the book we go through the whole process of building an API with Laravel and an SPA with Nuxt 3. We then deploy to web, iOS and Android. It’s a lot more cohesive and goes from empty code to production app!