This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

semble / src / webapp / hooks / useUrlMetadata.ts
2.4 kB 90 lines
1import { useState, useEffect, useCallback } from 'react'; 2import { ApiClient } from '@/api-client/ApiClient'; 3import type { UrlMetadata } from '@/components/UrlMetadataDisplay'; 4import type { GetUrlStatusForMyLibraryResponse } from '@/api-client/types'; 5 6interface UseUrlMetadataProps { 7 apiClient: ApiClient; 8 url?: string; 9 autoFetch?: boolean; 10} 11 12export function useUrlMetadata({ 13 apiClient, 14 url, 15 autoFetch = true, 16}: UseUrlMetadataProps) { 17 const [metadata, setMetadata] = useState<UrlMetadata | null>(null); 18 const [existingCardCollections, setExistingCardCollections] = useState< 19 GetUrlStatusForMyLibraryResponse['collections'] | null 20 >(null); 21 const [loading, setLoading] = useState(false); 22 const [error, setError] = useState<string | null>(null); 23 24 const fetchMetadata = useCallback( 25 async (targetUrl: string) => { 26 if (!targetUrl.trim()) return; 27 28 // Basic URL validation 29 try { 30 new URL(targetUrl); 31 } catch { 32 setError('Invalid URL format'); 33 return; 34 } 35 36 setLoading(true); 37 setError(null); 38 setExistingCardCollections(null); 39 40 try { 41 const response = await apiClient.getUrlMetadata(targetUrl); 42 setMetadata(response.metadata); 43 44 const existingCard = await apiClient.getUrlStatusForMyLibrary({ 45 url: targetUrl, 46 }); 47 48 // If there's an existing card, fetch its collections 49 if (existingCard.cardId) { 50 try { 51 setExistingCardCollections(existingCard.collections); 52 } catch (cardErr: any) { 53 console.error('Failed to fetch existing card details:', cardErr); 54 // Don't set error here as the metadata fetch was successful 55 } 56 } 57 } catch (err: any) { 58 console.error('Failed to fetch URL metadata:', err); 59 setError('Failed to load page information'); 60 setMetadata(null); 61 setExistingCardCollections(null); 62 } finally { 63 setLoading(false); 64 } 65 }, 66 [apiClient], 67 ); 68 69 // Auto-fetch when URL changes 70 useEffect(() => { 71 if (autoFetch && url) { 72 fetchMetadata(url); 73 } 74 }, [url, autoFetch, fetchMetadata]); 75 76 const refetch = useCallback(() => { 77 if (url) { 78 fetchMetadata(url); 79 } 80 }, [url, fetchMetadata]); 81 82 return { 83 metadata, 84 existingCardCollections, 85 loading, 86 error, 87 fetchMetadata, 88 refetch, 89 }; 90}