Created
October 12, 2024 07:51
-
-
Save AsadSaleh/93eb9071c303e1f55efcc9b6447a79a0 to your computer and use it in GitHub Desktop.
Function that receive our usual action, which return with { data, error }, and adjust it to throw when the `error` is not null. This is to comply with react-query's error handling.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function wrapApiCall< | |
T extends (...args: any[]) => Promise<{ data: any; error: any }>, | |
>( | |
apiCall: T, | |
): ( | |
...args: Parameters<T> | |
) => Promise< | |
ReturnType<T> extends Promise<{ data: infer TData; error: infer TError }> | |
? TData | |
: never | |
> { | |
return async (...args: Parameters<T>) => { | |
const response = await apiCall(...args); | |
if (response.error) { | |
throw response.error; | |
} | |
return response.data | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment