Nuxt Tip: Refresh Data by Watching Sources Using useAsyncData
Michael Hoffmann
@mokkapps
Nuxt 3's useAsyncData() composable can be used within your pages, components, and plugins to get access to data that resolves asynchronously.
In many scenarios (pagination, filtering results, searching, etc.), you may need to refresh the data loaded from the API based on user action. You can use the refresh()
method that is returned from the useAsyncData
composable.
refresh()
method is also returned by the useFetch
, useLazyFetch
, and use useLazyAsyncData
composables. For more information, check the official docs.Example refreshing data using the refresh method
Let's take a look at a simple code example using refresh
:
<script setup lang="ts">
const page = ref(1)
const { data: posts, refresh } = await useAsyncData('posts', () =>
$fetch('https://yourDomain.com/posts', {
params: {
page: page.value,
},
})
)
function previous() {
page.value--
refresh()
}
function next() {
page.value++
refresh()
}
</script>
By default, Nuxt waits until a refresh is finished before it can be executed again.
Example with watching params change
Nuxt provides an alternative for the refresh()
method which I prefer: the watch option.
This built-in option watches a list of reactive sources and automatically reruns the fetcher function when any changes in these sources are detected.
Let's take a look at the above example using the watch
option:
<script setup lang="ts">
const page = ref(1)
const { data: posts } = await useAsyncData(
'posts',
() =>
$fetch('https://yourDomain.com/posts', {
params: {
page: page.value,
},
}),
{ watch: [page] }
)
function previous() {
page.value--
}
function next() {
page.value++
}
</script>
If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :