andreiduca / use-async-resource

A custom React hook for simple data fetching with React Suspense
https://dev.to/andreiduca/practical-implementation-of-data-fetching-with-react-suspense-that-you-can-use-today-273m
ISC License
94 stars 9 forks source link

useAsyncResource ArgTypes extends unknown[] too narrow #93

Closed sami616 closed 2 years ago

sami616 commented 2 years ago

Hi, i've got a particular use case where the return and arg types for my async function cannot be inferred due to them needing to be passed as generics when called.

I noticed that the useAsyncResource hook accepts 2 generics, the first being the return type and second being the params.

This is great, as i can pass my own generics when calling the hook, the only issue i have is that the generic for args extends unknown[].

My arg type is an object, not an array meaning i get a TS error. Is this by design? It seems to be that enforcing something that extends an array is a bit too narrow?

andreiduca commented 2 years ago

Hey @sami616

The second is an array because the params get destructured. If your function has only one param and that's of a specific generic type, then the second generic you need to pass to useAsyncResource is that type as an array. Something like this:

function apiFn<CustomType>(param: CustomType): Promise<ResponseType> {
  return fetch(...).then(r => r.json() as ResponseType);
}

...

const [data] = useAsyncResource<ResponseType, [CustomType]>(apiFn, objParam);

If your function has multiple arguments, all generic, again you should pass them as part of an array:

function apiFn<T, U, V>(a: T, b: U, c: V): Promise<ResponseType> {
  return fetch(...).then(r => r.json() as ResponseType);
}

...

const [data] = useAsyncResource<ResponseType, [CustomType1, CustomType2, CustomType3]>(apiFn, param1, param2, param3);

But you should not have to pass any generics to the hook at all, as it is pretty good at inferring all of them for you:

Screen Shot 2021-11-09 at 2 01 42 PM

If your case is different, please share more details so I can better help you more specifically.

sami616 commented 2 years ago

okay this makes sense, thanks. I've managed to solve the issue i had 👍🏼