首页 > 解决方案 > react-query 不会停止重试获取 API

问题描述

我想通过以下方式实现这个场景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 秒后重试按钮...

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

标签: javascriptreactjsreact-query

解决方案


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>
  )
}

推荐阅读