docs: update data fetching for `$fetch` and refresh (#3914)

This commit is contained in:
Dan Pastori 2022-04-04 01:10:10 -07:00 committed by GitHub
parent 61180648ca
commit d5b7b5882c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 39 additions and 1 deletions

View File

@ -169,7 +169,34 @@ watch(posts, (newPosts) => {
</script>
```
## `refreshNuxtData`
## Refreshing Data
Sometimes throughout the course of your user's page visit, you may need to refresh the data loaded from the API. This can happen if the user chooses to paginate, filter results, search, etc.
You can make use of the `refresh()` method returned from the `useAsyncData()` composable to refresh the data with different query parameters:
```vue
<script setup>
const page = ref(1);
const { data:users, loading, refresh, error } = await useFetch(() => `users?page=${page.value}&take=6`, { baseURL: config.API_BASE_URL }
);
function previous(){
page.value--;
refresh();
}
function next() {
page.value++;
refresh();
}
</script>
```
The key to making this work is to call the `refresh()` method returned from the `useFetch()` composable when a query parameter has changed.
### `refreshNuxtData`
Invalidate the cache of `useAsyncData`, `useLazyAsyncData`, `useFetch` and `useLazyFetch` and trigger the refetch.
@ -329,3 +356,14 @@ export default defineComponent({
</header>
</template>
```
## Directly calling an API Endpoint
There are instances where you may need to directly call the API. Nuxt 3 provides a globally available `$fetch` method using [unjs/ohmyfetch](https://github.com/unjs/ohmyfetch) (in addition to `fetch`)
with the same API as the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).
Using `$fetch` has a number of benefits, including:
It will handle 'smartly' making direct API calls if it's running on the server, or making a client-side call to your API if it's running on the client. (It can also handle calling third-party APIs.)
Plus, it comes with convenience features including automatically parsing responses and stringifying data.