docs: add example of typing custom useFetch errors (#29253)

This commit is contained in:
Jeel Rupapara 2024-10-08 18:46:51 +05:30 committed by Daniel Roe
parent f188258016
commit cb6cd82b8c
No known key found for this signature in database
GPG Key ID: CBC814C393D93268

View File

@ -96,6 +96,28 @@ const { data: modules } = await useAPI('/modules')
</script>
```
If you want to customize the type of any error returned, you can also do so:
```ts
import type { FetchError } from 'ofetch'
import type { UseFetchOptions } from 'nuxt/app'
interface CustomError {
message: string
statusCode: number
}
export function useAPI<T>(
url: string | (() => string),
options?: UseFetchOptions<T>,
) {
return useFetch<T, FetchError<CustomError>>(url, {
...options,
$fetch: useNuxtApp().$api
})
}
```
::note
This example demonstrates how to use a custom `useFetch`, but the same structure is identical for a custom `useAsyncData`.
::