mkstack/src/hooks/useAuthor.ts
2025-04-17 11:23:46 -05:00

33 lines
884 B
TypeScript

import { type NostrEvent, type NostrMetadata, NSchema as n } from '@nostrify/nostrify';
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
export function useAuthor(pubkey: string | undefined) {
const { nostr } = useNostr();
return useQuery<{ event?: NostrEvent; metadata?: NostrMetadata }>({
queryKey: ['author', pubkey ?? ''],
queryFn: async ({ signal }) => {
if (!pubkey) {
return {};
}
const [event] = await nostr.query(
[{ kinds: [0], authors: [pubkey!], limit: 1 }],
{ signal: AbortSignal.any([signal, AbortSignal.timeout(500)]) },
);
if (!event) {
return {};
}
try {
const metadata = n.json().pipe(n.metadata()).parse(event.content);
return { metadata, event };
} catch {
return { event };
}
},
});
}