在使用 TypeScript 的 ReactQuery 过程中出现了事件类型定义错误。

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

Error during event typing from ReactQuery using TypeScript

问题

我在React应用程序中使用React Query来处理异步请求,遇到了从React Query库中对refetch方法进行类型定义的问题。

Component.tsx:

// 这里是在组件中定义的useQuery
...
const { data: notes = [], isLoading, isError, refetch } = useQuery<INotesList[]>(
    'notes',
    fetchNotes,
    {retry: 1, refetchOnWindowFocus: false, keepPreviousData: true}
)
...
// 在按钮的点击事件上使用refetch
<button
    onClick={(e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => refetch(e)}>
    重试
</button>

但是,上面使用的类型定义并不正确,因为在我看来,需要将事件传递给refetch方法,这个事件由按钮处理,但是这种选项是不可能的,当我尝试时,会出现错误。

TS2559: 类型'MouseEvent'与类型'RefetchOptions & RefetchQueryFilters'没有共同的属性。

如果我不为事件添加类型并将其传递为

onClick={refetch}

一切都能正常工作,但是这段代码部分将没有明确的类型定义。总体上,是否有可能为这种类型的事件添加类型呢?

提前感谢所有答复!

英文:

I use React Query to work with async requests in a React application, and I ran into the problem of typing the refetch method from the React Query library.

Component.tsx:

// Here is how useQuery defined in component
...
    const { data: notes = [], isLoading, isError, refetch } = useQuery&lt;INotesList[]&gt;(
        &#39;notes&#39;,
        fetchNotes,
        {retry: 1, refetchOnWindowFocus: false, keepPreviousData: true})
...
// Usage of refetch on button by click event
     &lt;button
                onClick={(e: React.MouseEvent&lt;HTMLButtonElement, MouseEvent&gt;) =&gt; refetch(e)}&gt;
                Retry
    &lt;/button&gt;

But, the typing that was used above does not work correctly, because in my opinion it is necessary to pass to the refetch method an event that is processed by this button, but this option is not possible, when I try, I get an error.

> TS2559: Type 'MouseEvent ' has no properties in common with type
> 'RefetchOptions & RefetchQueryFilters '.

If I don't add type to the event and pass it as

onClick={refetch}

everything works correctly, but this section of code remains without explicit typing.
Is it possible to add type to this kind of event in general?
Thank you for all answers in advance!

答案1

得分: 0

感谢 @nullptr,问题已解决:onClick={() => refetch}

英文:

Thanks to @nullptr, issue was solved: onClick={() =&gt; refetch}

huangapple
  • 本文由 发表于 2023年3月9日 20:43:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684795.html
匿名

发表评论

匿名网友

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

确定