mirror of
https://github.com/nuxt/nuxt.git
synced 2025-01-18 17:35:57 +00:00
update: docs
This commit is contained in:
parent
b04bf764e3
commit
d4cab63e04
@ -69,10 +69,11 @@ Wrapping with [`useAsyncData`](/docs/api/composables/use-async-data) **avoid dou
|
||||
Now that `$api` has the logic we want, let's create a `useAPI` composable to replace the usage of `useAsyncData` + `$api`:
|
||||
|
||||
```ts [composables/useAPI.ts]
|
||||
import type { NitroFetchRequest } from 'nitropack'
|
||||
import type { UseFetchOptions } from 'nuxt/app'
|
||||
|
||||
export function useAPI<T>(
|
||||
url: string | (() => string),
|
||||
url: NitroFetchRequest,
|
||||
options?: UseFetchOptions<T>,
|
||||
) {
|
||||
return useFetch(url, {
|
||||
@ -90,18 +91,10 @@ const { data: modules } = await useAPI('/modules')
|
||||
</script>
|
||||
```
|
||||
|
||||
Let's use the new composable and have a nice and clean component:
|
||||
|
||||
```vue [app.vue]
|
||||
<script setup>
|
||||
const { data: modules } = await useAPI('/modules')
|
||||
</script>
|
||||
```
|
||||
|
||||
If you want to customize the type of any error returned, you can also do so:
|
||||
|
||||
```ts twoslash
|
||||
import type { FetchError } from 'ofetch'
|
||||
import type { NitroFetchRequest } from 'nitropack'
|
||||
import type { UseFetchOptions } from 'nuxt/app'
|
||||
|
||||
interface CustomError {
|
||||
@ -110,10 +103,10 @@ interface CustomError {
|
||||
}
|
||||
|
||||
export function useAPI<T>(
|
||||
url: string | (() => string),
|
||||
url: NitroFetchRequest,
|
||||
options?: UseFetchOptions<T>,
|
||||
) {
|
||||
return useFetch<T, FetchError<CustomError>>(url, {
|
||||
return useFetch<T, CustomError>(url, {
|
||||
...options,
|
||||
$fetch: useNuxtApp().$api
|
||||
})
|
||||
|
Loading…
Reference in New Issue
Block a user