Javascript is required
·
1 min read

Nuxt Tip: Refresh Data by Watching Sources Using useAsyncData

Nuxt Tip: Refresh Data by Watching Sources Using useAsyncData Image

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.

Info

The 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:

Component.vue
1<script setup lang="ts">
2const page = ref(1)
3
4const { data: posts, refresh } = await useAsyncData('posts', () =>
5  $fetch('https://yourDomain.com/posts', {
6    params: {
7      page: page.value,
8    },
9  })
10)
11
12function previous() {
13  page.value--
14  refresh()
15}
16
17function next() {
18  page.value++
19  refresh()
20}
21</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:

Component.vue
1<script setup lang="ts">
2const page = ref(1)
3
4const { data: posts } = await useAsyncData(
5  'posts',
6  () =>
7    $fetch('https://yourDomain.com/posts', {
8      params: {
9        page: page.value,
10      },
11    }),
12  { watch: [page] }
13)
14
15function previous() {
16  page.value--
17}
18
19function next() {
20  page.value++
21}
22</script>

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.