首页 > 解决方案 > 我想每 3 秒更新一次,而不使用 react apollo refetch

问题描述

我正在使用反应阿波罗。
我想每 3 秒更新一次进度条组件的 user.percent,而不使用 apllo 的重新获取。

import {useInterval} from 'beautiful-react-hooks';

const ProgressBar = () => {
  const {userId} = useParams<{userId: string}>();
  const {data: {user = null} = {}, refetch: refetchUser} =
    useUserQuery({
      variables: {uuid: userId},
      skip: !userId,
    });
  if (!user) return null;

  useInterval(() => {
    refetchUser();
  }, 3000);

  return (
     <p>{user.percent}</p>
  )
}

标签: reactjstypescriptapollo

解决方案


您可以使用Apollo 的轮询功能每隔 X 毫秒执行一次查询。

  const {data: {user = null} = {}, startPolling, stopPolling} = useUserQuery({
      variables: {uuid: userId},
      skip: !userId,
      pollInterval: 3000, // <-- refetch every 3 sec

    });

startPolling您可以分别使用和stopPolling函数启动和暂停/停止轮询。


推荐阅读