react – concurrent fetch using Promise.all

◾️ fetch A data and fetch B data

....
const Detail = () => {
  const { globalState, setGlobalState } = useContext(Store);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const location = useLocation();
  console.log("Detail:", location);

  const fetchDetailData = async () => {
    const searchParams = new URLSearchParams(location.search);
    const id = searchParams.get("v");

    try {
      if (id) {
        const {
          data: { items: selected },
        } = await youtubeApi.detailVideo(id);

        const {
          data: { items: related },
        } = await youtubeApi.relatedVideo(id);

        setGlobalState({
          type: "SET_DETAIL",
          payload: { detail: selected ? selected[0] : "" },
        });

        setGlobalState({ type: "SET_RELATED", payload: { side: related } });
      }
    } catch {
      setError("fetch data error");
      setTimeout(() => {
        setError("");
      }, 2000);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDetailData();
  }, [location.search]);
....

◾️ fetch A and B data concurrently using Promise.all

....
const Detail = () => {
  const { globalState, setGlobalState } = useContext(Store);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const location = useLocation();
  console.log("Detail:", location);

  const fetchDetailData = async () => {
    const searchParams = new URLSearchParams(location.search);
    const id = searchParams.get("v");

    try {
      if (id) {
        const [
          {
            data: { items: selected },
          },
          {
            data: { items: related },
          },
        ] = await Promise.all([
          youtubeApi.detailVideo(id),
          youtubeApi.relatedVideo(id),
        ]);

        setGlobalState({
          type: "SET_DETAIL",
          payload: { detail: selected ? selected[0] : "" },
        });

        setGlobalState({ type: "SET_RELATED", payload: { side: related } });
      }
    } catch {
      setError("fetch data error");
      setTimeout(() => {
        setError("");
      }, 2000);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDetailData();
  }, [location.search]);
....

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です