Closed sami616 closed 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:
If your case is different, please share more details so I can better help you more specifically.
okay this makes sense, thanks. I've managed to solve the issue i had 👍🏼
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?