javascript 我有两个API调用,我想合并这两个API调用数据

zpjtge22  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(172)

我这样做了,它的工作,但我填补这不是一个很好的方式编写代码,我需要使它更干净,我也使用了3个不同的国家,我也服务没有帮助,让我知道是任何更好的方式,使代码干净,我需要使它有用

const [pendingArtifactsCount, setPendingArtifactsCount] = useState([]);
  const [pendingDatasetCount, setPendingDatasetCount] = useState([]);
  const [pendingProjectCount, setPendingProjectCount] = useState([]);

  const updatePendingArtifactsCount = () => {
    fetchSentReceivedProject().then((res) => {
      const pendingData =
        res.data.received?.length >= 1 &&
        res.data.received?.filter(
          (data) => data?.receiver_status === 'PENDING'
        );
      setPendingProjectCount(pendingData);
    });
    fetchSentReceivedArtifacts((res) => {
      const pendingData =
        res.data.recieved?.length >= 1 &&
        res.data.recieved?.filter(
          (data) =>
            data?.recieverStatus === 'Pending' && data.ispresent === true
        );
      setPendingDatasetCount(pendingData);
    });
  };

  React.useEffect(() => {
    setPendingArtifactsCount([...pendingDatasetCount, ...pendingProjectCount]);
  }, [pendingDatasetCount, pendingProjectCount]);
py49o6xq

py49o6xq1#

所以你也可以像下面的代码一样只创建一个状态,并使用let变量来存储值。

const [allCounts, setAllCounts] = useState([]);

const updatePendingArtifactsCount = () => {
    let projectCount = [];
    let artifactsCount = [];
    fetchSentReceivedProject().then((res) => {
      projectCount =
        res.data.received?.length >= 1 &&
        res.data.received?.filter(
          (data) => data?.receiver_status === 'PENDING'
        );
    });
    fetchSentReceivedArtifacts((res) => {
      artifactsCount =
        res.data.recieved?.length >= 1 &&
        res.data.recieved?.filter(
          (data) =>
            data?.recieverStatus === 'Pending' && data.ispresent === true
        );
    });
  setAllCounts([...projectCount,...artifactsCount]);
};

相关问题