/ src / hooks / useLoggedInAccounts.ts
useLoggedInAccounts.ts
 1  import { useNostr } from '@nostrify/react';
 2  import { useNostrLogin } from '@nostrify/react/login';
 3  import { useQuery } from '@tanstack/react-query';
 4  import { NSchema as n, NostrEvent, NostrMetadata } from '@nostrify/nostrify';
 5  
 6  export interface Account {
 7    id: string;
 8    pubkey: string;
 9    event?: NostrEvent;
10    metadata: NostrMetadata;
11  }
12  
13  export function useLoggedInAccounts() {
14    const { nostr } = useNostr();
15    const { logins, setLogin, removeLogin } = useNostrLogin();
16  
17    const { data: authors = [] } = useQuery({
18      queryKey: ['nostr', 'logins', logins.map((l) => l.id).join(';')],
19      queryFn: async ({ signal }) => {
20        const events = await nostr.query(
21          [{ kinds: [0], authors: logins.map((l) => l.pubkey) }],
22          { signal: AbortSignal.any([signal, AbortSignal.timeout(1500)]) },
23        );
24  
25        return logins.map(({ id, pubkey }): Account => {
26          const event = events.find((e) => e.pubkey === pubkey);
27          try {
28            const metadata = n.json().pipe(n.metadata()).parse(event?.content);
29            return { id, pubkey, metadata, event };
30          } catch {
31            return { id, pubkey, metadata: {}, event };
32          }
33        });
34      },
35      retry: 3,
36    });
37  
38    // Current user is the first login
39    const currentUser: Account | undefined = (() => {
40      const login = logins[0];
41      if (!login) return undefined;
42      const author = authors.find((a) => a.id === login.id);
43      return { metadata: {}, ...author, id: login.id, pubkey: login.pubkey };
44    })();
45  
46    // Other users are all logins except the current one
47    const otherUsers = (authors || []).slice(1) as Account[];
48  
49    return {
50      authors,
51      currentUser,
52      otherUsers,
53      setLogin,
54      removeLogin,
55    };
56  }