-
I am getting started with react-query and we have an Axios API library automatically generated from Swagger. Additionally many many of our REST endpoints always return the same data structure on an error and we have our own internal error codes. To handle the myriad of errors that can possibly go wrong when making an API call, I have created a Here is a sort of mock example of what this gives us where we can super easily match our standard API error for an INVALID_FILTER code and extract the detailedMessage from the data for use. Or we match a 403 response, otherwise we handle the unknown error. const TaskInfo = ({id}: {id: number}) => {
const { data, isLoading, isError, error } = useQuery({
queryKey: ['getTask', id],
queryFn: () => getTask(id)
});
if(isLoading) return <Loader />
if(isError) return match(parseError(error))
.with({type: 'ApiError, errorCode: INVALID_FILTER, detailedMessage: P.select()}, (message) => <InvalidFilterError message={message} />)
.with({type: 'HttpError', code: 403}, () => <NotAuthorisedError />)
.otherwise(() => <UnknownError />)
return <TaskContent task={data} />
} Now my problem. However, I can not for the life of me figure out how to properly type a hook that updates the error type. Essentially what I am looking at is how I could write a hook like this, but without Typescript errors. const useGetTask = (id: number): UseQueryResult<Task, ErrorResult> => {
const result = useQuery({
queryKey: ['getTask', id],
queryFn: () => getTask(id)
});
if(result.isError){
result.error = parseError(result.error);
return result;
}
return result;
} Here is a reproduction. You can ignore the majority of the Any thoughts? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
it looks like re-assigning
however, it still doesn't check out because you
|
Beta Was this translation helpful? Give feedback.
it looks like re-assigning
result.error
doesn't change the type oferror
. I think you would need a type assertion here:however, it still doesn't check out because you
return result
at the very end, and there, you haven't transformed the error. Is there a reason why you can't always callparseError
and handle the null check inside of it? That would enable you to at least do: