question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Generic response type not working with `useFetch`

See original GitHub issue

Versions

  • nuxt: 3.0.0-rc.12 & 3.0.0-rc.13
  • node: v16.11.0

Reproduction

https://stackblitz.com/edit/github-itsfns?file=app.vue

Works fine (asyncData is a _AsyncData<{ title: string }, true | FetchError<any> | null>:

const customApi = async () => {
	const asyncData = await useFetch<{ title: string }>('https://api.nuxtjs.dev/mountains', {
		pick: ['title'],
		method: 'GET',
	});
	return asyncData;
};
const result  = await customApi();
console.log(result.data.value?.title);

Not working (asyncData is a _AsyncData<PickFrom<_ResT, KeyOfRes<Transform>>, true | FetchError<any> | null>):

const customApi = async <T>() => {
	const asyncData = await useFetch<T>('https://api.nuxtjs.dev/mountains', {
		pick: ['title'],
		method: 'GET',
	});
	return asyncData;
};
const result  = await customApi<{ title: string }>();
console.log(result.data.value?.title);

Additionally, setting the `pick1 field causes an error.

Additional Details
I would like to add that everything worked very well before. Unfortunately, now even undoing the Nuxt version doesn't help.

Steps to reproduce

Copy and paste code above.

What is Expected?

I want to create a custom useFetch and be able to type a response (link1, link2)

What is actually happening?

I am getting a weird type causing my application to fail.

Issue Analytics

  • State:closed
  • Created 10 months ago
  • Comments:13 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
danielroecommented, Nov 8, 2022

In that case, you can copy the types from useFetch with their inference. It’s a complex type but it needs to be for the inference:

https://github.com/nuxt/framework/blob/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c/packages/nuxt/src/app/composables/fetch.ts#L23-L33

The other alternative is to simply override them, e.g.:

const customApi = async <T>(request: NitroFetchRequest, options: UseFetchOptions<T extends void ? unknown : T, (res: T extends void ? unknown : T) => T extends void ? unknown : T, KeyOfRes<(res: T extends void ? unknown : T) => T extends void ? unknown : T>>) => {
	const statusCode = ref<number>(200);
	const asyncData = await useFetch(request, {
		initialCache: false,
		baseURL: <url>,
		headers: { ...headers, authorization: localStorage['auth-token'] }, // current localStorage
		onResponseError: async (ctx) => {
			statusCode.value = ctx.response.status;
			await onResponseError(ctx);
		},
		onRequest,
		parseResponse,
		...options,
	}) as AsyncData<T, FetchError | null>;
	return { ...asyncData, statusCode };
};
0reactions
szulcuscommented, Nov 9, 2022

Yes, I know. I mean a ready type with missing fields returned by useFetch (status, statusCode, statusMessage, statusText). These fields are not dependent on me. I hope this can be completed in the future. Temporarily I’ll do it manually like this:

AsyncData<T, (FetchError<ApiError> & { status: number }) | null>

I’m not bothered anymore, thank you for your time and help.

Read more comments on GitHub >

github_iconTop Results From Across the Web

set types to useFetch using generics with typescript
The problem I have is that it does not recognize the result. I am using generic types in useFetch. If I use the...
Read more >
How to Use fetch with TypeScript -- newline - Fullstack.io
The main problem with fetch function is that it isn't a generic function. This makes it harder to type response data without writing ......
Read more >
useFetch
If retryOn: [400] and retries > 0 then we only retry on a response status of 400 , not on any generic network...
Read more >
How To Write a Custom useFetch Hook For API Calls
Step 1: Define a custom hook · Step 2: Optional callback function to process response · Step 3: Generic type.
Read more >
useFetch - Raycast API
useFetch. Hook which fetches the URL and returns the AsyncState ... By default, the hook will return response.json() if the response has a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found