Nuxt Tip: Refresh Data by Watching Sources Using useAsyncData
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
:
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:
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:
Vue Tip: When to Use Render Function
When should I use a render function in Vue.js? We’re going to cover some advanced Vue.js patterns when you need to use render functions.
Vue Tip: Validate Events and Prop Types
You can validate prop types and events in Vue. If a requirement is not met, Vue will warn you in the browser's JavaScript console.