From 280e5923ea9bb0bbf69799945c5693483572e7e3 Mon Sep 17 00:00:00 2001 From: Jeel Rupapara Date: Tue, 8 Oct 2024 18:46:51 +0530 Subject: [PATCH] docs: add example of typing custom `useFetch` errors (#29253) --- docs/2.guide/4.recipes/3.custom-usefetch.md | 22 +++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/2.guide/4.recipes/3.custom-usefetch.md b/docs/2.guide/4.recipes/3.custom-usefetch.md index e8f25f6a2b..1391720db3 100644 --- a/docs/2.guide/4.recipes/3.custom-usefetch.md +++ b/docs/2.guide/4.recipes/3.custom-usefetch.md @@ -96,6 +96,28 @@ const { data: modules } = await useAPI('/modules') ``` +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( + url: string | (() => string), + options?: UseFetchOptions, +) { + return useFetch>(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`. ::