useDMContext.ts
1 import { useContext } from "react"; 2 import { DMContext, DMContextType } from "@/contexts/DMContext"; 3 4 /** 5 * Hook to access the direct messaging system. 6 * 7 * Provides access to conversations, message sending, loading states, and cache management. 8 * Must be used within a DMProvider. 9 * 10 * @example 11 * ```tsx 12 * import { useDMContext } from '@/hooks/useDMContext'; 13 * import { MESSAGE_PROTOCOL } from '@/lib/dmConstants'; 14 * 15 * function MyComponent() { 16 * const { conversations, sendMessage, isLoading } = useDMContext(); 17 * 18 * // Send a message 19 * await sendMessage({ 20 * recipientPubkey: 'hex-pubkey', 21 * content: 'Hello!', 22 * protocol: MESSAGE_PROTOCOL.NIP17 23 * }); 24 * 25 * // Display conversations 26 * return ( 27 * <div> 28 * {isLoading ? 'Loading...' : conversations.map(c => ( 29 * <div key={c.pubkey}>{c.lastMessage?.decryptedContent}</div> 30 * ))} 31 * </div> 32 * ); 33 * } 34 * ``` 35 * 36 * @returns DMContextType - The direct messaging context 37 * @throws Error if used outside DMProvider 38 */ 39 export function useDMContext(): DMContextType { 40 const context = useContext(DMContext); 41 if (!context) { 42 throw new Error('useDMContext must be used within DMProvider'); 43 } 44 return context; 45 }