英文:
What's the correct way of typing an error in react-query?
问题
我想能够为 react-query 的 useQuery
钩子提供一个自定义错误(正确类型化)。自定义错误的原因是,如果请求失败,我希望能够提供响应的 status
码,以便根据该状态决定是否使用 useErrorBoundary
选项。
我已经阅读过了,像这样为 useQuery
提供泛型并不是一个很好的主意:
const { data, isLoading } = useQuery<DataType, CustomErrorType>(
['example'],
() => getData(),
{
useErrorBoundary: (error) => error.status >= 500
}
)
更好的做法是让 react-query 通过为 queryFn
添加类型来自动推断类型。如果我使用 axios
,这不会是一个问题,因为它提供了一些用于处理错误的实用程序和类型,但我正在使用 fetch
。
那么,在这种情况下,获得正确类型化的自定义错误的最佳方法是什么呢?
英文:
I want to be able to provide a custom error (properly typed) to react-query's useQuery
hook. The reason for this custom error is to be able to provide to it the status
code of the response in case it fails, so I can determine whether or not to use the useErrorBoundary
option based on that status.
I've read that it's not a very good idea to provide generics to useQuery
like so:
const { data, isLoading } = useQuery<DataType, CustomErrorType>(
['example'],
() => getData(),
{
useErrorBoundary: (error) => error.status >= 500
}
)
And that it's a better idea to let react-query infer the types by typing the queryFn
instead. If I were using axios
this wouldn't be an issue since it provides some utilities and types for errors, but I'm working with fetch
.
So, what would be the best way to get a correctly typed custom error in this case?
答案1
得分: 1
Error
类型可以从所有“位置”中推断出来,所以如果你为useErrorBoundary
提供了类型注解,它就会起作用:
const { data, isLoading } = useQuery(
['example'],
() => getData(),
{
useErrorBoundary: (error: CustomErrorType) => error.status >= 500
}
)
这将使Data
的类型仍然从queryFn中推断出来(并消除手动传递泛型引起的所有其他问题),而error
仍将是CustomErrorType
。
英文:
the Error
type can be inferred from all "places", so it works if you provide a type annotation to useErrorBoundary
:
const { data, isLoading } = useQuery(
['example'],
() => getData(),
{
useErrorBoundary: (error: CustomErrorType) => error.status >= 500
}
)
this will make the type of Data
still be inferred from the queryFn (and eliminate all other problems that come from passing generics manually), and error
will still be CustomErrorType
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论