【问题标题】:react-query doesn't stop retrying to fetch an APIreact-query 不会停止重试获取 API
【发布时间】:2021-11-08 11:30:47
【问题描述】:

我想通过react-query实现这个场景:

我的组件获取了一个 API,并且应该在客户端的 Internet 断开连接时尝试一次,并且如果 Internet 重新连接,则永远不会重新获取...如果重试不成功,则在 3 秒后,应该显示一个错误,并带有一个用于重试的按钮请求。

const URL = 'https://randomuser.me/api/?results=5&inc=name';

const Example = () => {
  const { error, data, isLoading, refetch } = useQuery('test', () =>
    fetch(URL).then(response => response.json()).then(data => data.results), {
    refetchOnWindowFocus: false,
    refetchOnReconnect: false,
    retry: 1,
    retryDelay: 3000
  });

  if (isLoading) return <span>Loading...</span>

  if (error) return <span>Error: {error.message} <button onClick={refetch}>retry</button></span>

  return (
    <div>
      <h1>Length: {data ? console.log(data.length) : null}</h1>
      <button onClick={refetch}>Refetch</button>
    </div>
  )
}

考虑到上面的代码,我将refetchOnReconnect: false设置为禁用连接互联网后重新获取,retry: 1设置一次尝试,retryDelay: 3000设置重试时间限制。

但是当我在 DevTools 中使用 Throttling -> offline 时,单击按钮后仅显示最后一个结果,3 秒后不显示错误和重试按钮...

那么,有什么方法可以处理这个功能吗?

【问题讨论】:

    标签: javascript reactjs react-query


    【解决方案1】:

    React-query正在使用缓存中的数据,您应该通过调用函数invalidateQueries使查询无效以再次获取数据:

    onst URL = 'https://randomuser.me/api/?results=5&inc=name'
    
    const Example = () => {
      // Get QueryClient from the context
      const queryClient = useQueryClient()
      const { error, data, isLoading, refetch } = useQuery(
        'test',
        () =>
          fetch(URL)
            .then(response => response.json())
            .then(data => data.results),
        {
          refetchOnWindowFocus: false,
          refetchOnReconnect: false,
          retry: 1,
          retryDelay: 3000
        }
      )
    
      const buttonClickHandler = () => queryClient.invalidateQueries('test') // <=== invalidate the cache
    
      if (isLoading) return <span>Loading...</span>
    
      if (error)
        return (
          <span>
            Error: {error.message} <button onClick={refetch}>retry</button>
          </span>
        )
    
      return (
        <div>
          <h1>Length: {data ? console.log(data.length) : null}</h1>
          <button onClick={buttonClickHandler}>Refetch</button>
        </div>
      )
    }
    

    【讨论】:

    • 但是在这种情况下,我必须为每个页面导入 queryClient ......我认为这不是最佳实践,这个包应该在内部处理这个问题
    猜你喜欢
    • 2019-11-17
    • 2021-06-19
    • 2023-01-30
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多