竞态排序:连续发送的请求只获取最后一个

47 阅读1分钟

竞态排序:连续发送的请求只获取最后一个 常见场景:分页、tab切换、搜索,用户多次连续触发请求,我们只取最后一个

下面为简单封装的一个hook

const useMyReauest = (url) => {
  const [url, setUrl] = useState("");
  const [loading, setLoading] = useState(false);
  const [data, setDate] = useState(null);
  const countRef = useRef(0);
  const [error, setError] = useState(null);

  const fetchDate = useCallBack(async () => {
    countRef.current++;
    const currentIndex = countRef.current;
    try {
      setLoading(true);
      setError(null);
      const res = await axios.get(url);
      if (currentIndex === countRef.current) {
        setDate(res.data);
      }
    } catch (error) {
      if (currentRequestId === requestId) {
        setError(err);
      }

      // setError(error)
    } finally {
      if (currentRequestId === requestId) {
        setLoading(false);
      }
    }
  }, [url]);
  const triggerRequest = (newUrl: string) => {
    setUrl(newUrl);
  };

  return {
    fetchDate,
    data,
    triggerRequest,
  };
};