A React component library for rendering common AT Protocol records for applications such as Bluesky and Leaflet.
1import { useEffect, useState } from 'react'; 2import { useAtProto } from '../providers/AtProtoProvider'; 3 4/** 5 * Resolves the PDS service endpoint for a given DID and tracks loading state. 6 * 7 * @param did - DID whose PDS endpoint should be discovered. 8 * @returns {{ endpoint: string | undefined; error: Error | undefined; loading: boolean }} Object containing the resolved endpoint, error (if any), and loading flag. 9 */ 10export function usePdsEndpoint(did: string | undefined) { 11 const { resolver, didCache } = useAtProto(); 12 const [endpoint, setEndpoint] = useState<string | undefined>(); 13 const [error, setError] = useState<Error | undefined>(); 14 const [loading, setLoading] = useState(false); 15 16 useEffect(() => { 17 let cancelled = false; 18 if (!did) { 19 setEndpoint(undefined); 20 setError(undefined); 21 setLoading(false); 22 return () => { cancelled = true; }; 23 } 24 25 const cached = didCache.getByDid(did); 26 if (cached?.pdsEndpoint) { 27 setEndpoint(cached.pdsEndpoint); 28 setError(undefined); 29 setLoading(false); 30 return () => { cancelled = true; }; 31 } 32 33 setEndpoint(undefined); 34 setLoading(true); 35 setError(undefined); 36 didCache.ensurePdsEndpoint(resolver, did) 37 .then(snapshot => { 38 if (cancelled) return; 39 setEndpoint(snapshot.pdsEndpoint); 40 }) 41 .catch(e => { 42 if (cancelled) return; 43 setError(e as Error); 44 }) 45 .finally(() => { 46 if (!cancelled) setLoading(false); 47 }); 48 return () => { cancelled = true; }; 49 }, [did, resolver, didCache]); 50 51 return { endpoint, error, loading }; 52}