UNPKG

@react-native-youtube-bridge/react

Version:
87 lines (84 loc) 2.68 kB
import { ERROR_CODES, extractVideoIdFromUrl, validateVideoId } from "@react-native-youtube-bridge/core"; import { useEffect, useMemo, useState } from "react"; //#region src/hooks/useYoutubeVideoId.ts const useYouTubeVideoId = (source, onError) => { const sourceValue = useMemo(() => { if (!source) return; if (typeof source === "string") return source; if ("videoId" in source) return source.videoId; if ("url" in source) return source.url; return null; }, [typeof source === "string" ? source : source && "videoId" in source ? source.videoId : source && "url" in source ? source.url : null]); const videoId = useMemo(() => { if (sourceValue === null) { console.error("Invalid YouTube source: ", sourceValue); onError?.({ code: 1002, message: ERROR_CODES[1002] }); return null; } if (sourceValue === void 0) return void 0; if (validateVideoId(sourceValue)) return sourceValue; const extractedId = extractVideoIdFromUrl(sourceValue); if (!extractedId) { console.error("Invalid YouTube source: ", sourceValue); onError?.({ code: 1002, message: ERROR_CODES[1002] }); return null; } return extractedId; }, [sourceValue, onError]); return videoId; }; var useYoutubeVideoId_default = useYouTubeVideoId; //#endregion //#region src/hooks/useYoutubeOEmbed.ts /** * Hook to fetch the oEmbed data for a YouTube video. * @param url - The URL of the YouTube video. * @returns The oEmbed data, loading state, and error. */ const useYoutubeOEmbed = (url) => { const [oEmbed, setOEmbed] = useState(); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); useEffect(() => { if (!url) return; const controller = new AbortController(); setError(null); setOEmbed(void 0); const fetchOEmbed = async () => { setIsLoading(true); try { const response = await fetch(`https://www.youtube.com/oembed?format=json&url=${encodeURIComponent(url)}`, { signal: controller.signal }); if (!response.ok) throw new Error("Failed to fetch oEmbed"); const data = await response.json(); setOEmbed(data); } catch (error$1) { if (error$1 instanceof Error && error$1.name === "AbortError") return; if (error$1 instanceof Error) { setError(error$1); return; } setError(new Error("Failed to fetch oEmbed")); } finally { setIsLoading(false); } }; fetchOEmbed(); return () => { controller.abort(); }; }, [url]); return { oEmbed, isLoading, error }; }; var useYoutubeOEmbed_default = useYoutubeOEmbed; //#endregion export { useYoutubeVideoId_default as useYouTubeVideoId, useYoutubeOEmbed_default as useYoutubeOEmbed };