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 setLoading(true); 34 setError(undefined); 35 didCache.ensurePdsEndpoint(resolver, did) 36 .then(snapshot => { 37 if (cancelled) return; 38 setEndpoint(snapshot.pdsEndpoint); 39 }) 40 .catch(e => { 41 if (cancelled) return; 42 setError(e as Error); 43 }) 44 .finally(() => { 45 if (!cancelled) setLoading(false); 46 }); 47 return () => { cancelled = true; }; 48 }, [did, resolver, didCache]); 49 50 return { endpoint, error, loading }; 51}