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.3 kB 87 lines
1import { useState, useEffect, useCallback } from 'react'; 2import { ApiClient } from '@/api-client/ApiClient'; 3import type { UrlMetadata } from '@/components/UrlMetadataDisplay'; 4import type { UrlCardView } 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 [existingCard, setExistingCard] = useState<UrlCardView | null>(null); 19 const [loading, setLoading] = useState(false); 20 const [error, setError] = useState<string | null>(null); 21 22 const fetchMetadata = useCallback( 23 async (targetUrl: string) => { 24 if (!targetUrl.trim()) return; 25 26 // Basic URL validation 27 try { 28 new URL(targetUrl); 29 } catch { 30 setError('Invalid URL format'); 31 return; 32 } 33 34 setLoading(true); 35 setError(null); 36 setExistingCard(null); 37 38 try { 39 const response = await apiClient.getUrlMetadata(targetUrl); 40 setMetadata(response.metadata); 41 42 // If there's an existing card, fetch its details including collections 43 if (response.existingCardId) { 44 try { 45 const cardResponse = await apiClient.getUrlCardView( 46 response.existingCardId, 47 ); 48 setExistingCard(cardResponse); 49 } catch (cardErr: any) { 50 console.error('Failed to fetch existing card details:', cardErr); 51 // Don't set error here as the metadata fetch was successful 52 } 53 } 54 } catch (err: any) { 55 console.error('Failed to fetch URL metadata:', err); 56 setError('Failed to load page information'); 57 setMetadata(null); 58 setExistingCard(null); 59 } finally { 60 setLoading(false); 61 } 62 }, 63 [apiClient], 64 ); 65 66 // Auto-fetch when URL changes 67 useEffect(() => { 68 if (autoFetch && url) { 69 fetchMetadata(url); 70 } 71 }, [url, autoFetch, fetchMetadata]); 72 73 const refetch = useCallback(() => { 74 if (url) { 75 fetchMetadata(url); 76 } 77 }, [url, fetchMetadata]); 78 79 return { 80 metadata, 81 existingCard, 82 loading, 83 error, 84 fetchMetadata, 85 refetch, 86 }; 87}