update: docs

This commit is contained in:
xjccc 2024-11-29 16:19:55 +08:00
parent b04bf764e3
commit d4cab63e04

View File

@ -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`: 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] ```ts [composables/useAPI.ts]
import type { NitroFetchRequest } from 'nitropack'
import type { UseFetchOptions } from 'nuxt/app' import type { UseFetchOptions } from 'nuxt/app'
export function useAPI<T>( export function useAPI<T>(
url: string | (() => string), url: NitroFetchRequest,
options?: UseFetchOptions<T>, options?: UseFetchOptions<T>,
) { ) {
return useFetch(url, { return useFetch(url, {
@ -90,18 +91,10 @@ const { data: modules } = await useAPI('/modules')
</script> </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: If you want to customize the type of any error returned, you can also do so:
```ts twoslash ```ts twoslash
import type { FetchError } from 'ofetch' import type { NitroFetchRequest } from 'nitropack'
import type { UseFetchOptions } from 'nuxt/app' import type { UseFetchOptions } from 'nuxt/app'
interface CustomError { interface CustomError {
@ -110,10 +103,10 @@ interface CustomError {
} }
export function useAPI<T>( export function useAPI<T>(
url: string | (() => string), url: NitroFetchRequest,
options?: UseFetchOptions<T>, options?: UseFetchOptions<T>,
) { ) {
return useFetch<T, FetchError<CustomError>>(url, { return useFetch<T, CustomError>(url, {
...options, ...options,
$fetch: useNuxtApp().$api $fetch: useNuxtApp().$api
}) })