Skip to content

Instantly share code, notes, and snippets.

@AsadSaleh
Created October 12, 2024 07:51
Show Gist options
  • Save AsadSaleh/93eb9071c303e1f55efcc9b6447a79a0 to your computer and use it in GitHub Desktop.
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.
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