Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

Commit

Permalink
docs: update data fetching for $fetch and refresh (#3914)
Browse files Browse the repository at this point in the history
  • Loading branch information
danpastori committed Apr 4, 2022
1 parent 6118064 commit d5b7b58
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion docs/content/3.docs/1.usage/1.data-fetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.

0 comments on commit d5b7b58

Please sign in to comment.