如何返回错误,但继续在React Query中重试

发布于 2025-01-23 17:18:14 字数 586 浏览 2 评论 0原文

我正在使用 react-Query 从后端获取数据。

当用户查看页面时,可选的后端仍然没有数据,因此后端将返回404 ,用户将看到一个空态组件。

现在,我想在后台显示空态组件,但继续在后台进行 refetch /重试

如何使用React-Query实现这一目标?


我尝试使用“无限重试”,但是当react-Query重试时,它仍然返回isloading = true,并且我无法显示 emptystate 同时。

我还认为使用refetchinterval,但是例如,如果将其设置为30秒,我不希望返回数据时30分钟。

I'm using react-query to fetch the data from the backend.

When the user views the page, optionally there is still no data in the backend, so the backend will return 404, and the user will see an EmptyState component.

Now, I want to show the EmptyState component, but continue to refetch/retry in the background.

How can achieve that with react-query?


I tried to use "infinite retry", but when the react-query is retrying, it still returns isLoading = true, and I can't show the EmptyState meanwhile.

I also thought to use refetchInterval, but if, for example, I set it to 30 seconds, I don't want it to be 30 minutes when a data is returned.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

辞旧 2025-01-30 17:18:14

所有重试完成后,React-Query才会出现错误状态。我看到多个选项:

  1. 使用RefetchInterval,就像您自己建议一样。您可以将其设置为一个函数,以启用间隔是否启用,具体取决于数据:
refetchInterval: (data, query) => query.state === 'error' ? 5000 : 0

只要查询处于错误状态,就可以每5秒重新挖掘一次。如果成功,则间隔将禁用。

  1. 使用重试,React-Query将为您提供FailureCount:boolean使用useQuery返回。此计数将每次查询失败并在内部进行重试时进行更新。故障计数将在查询成功后立即返回0,或者,一旦您重新启动获取。

因此,您可以在failureCount>时显示空状态。 0

react-query will only go error state after all the retries have finished. I see multiple options:

  1. use refetchInterval like you suggested yourselves. You can set it to a function to derive if you want to enable the interval or not, depending on the data:
refetchInterval: (data, query) => query.state === 'error' ? 5000 : 0

this would refetch every 5 seconds for as long as the query is in error state. If it goes to success, the interval is disabled.

  1. use the retries, and react-query will give you a failureCount: boolean returned from useQuery. This count will update every time the query fails and gets retried internally. The failure count will go back to 0 as soon as the query is successful, or, as soon as you restart a fetch.

so you could display your empty state while failureCount > 0

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文