在React Query中正确的方式是如何输入错误?

huangapple go评论61阅读模式
英文:

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&lt;DataType, CustomErrorType&gt;(
  [&#39;example&#39;],
  () =&gt; getData(),
  {
    useErrorBoundary: (error) =&gt; error.status &gt;= 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

TypeScript playground here

英文:

the Error type can be inferred from all "places", so it works if you provide a type annotation to useErrorBoundary:

const { data, isLoading } = useQuery(
  [&#39;example&#39;],
  () =&gt; getData(),
  {
    useErrorBoundary: (error: CustomErrorType) =&gt; error.status &gt;= 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

TypeScript playground here

huangapple
  • 本文由 发表于 2023年1月9日 05:00:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75051255.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定