UNPKG

@api-buddy/sendgrid

Version:

API Buddy integration for SendGrid - Email delivery service for transactional and marketing emails

107 lines (95 loc) 2.61 kB
'use client'; import { useState, useCallback } from 'react'; import { sendEmail, sendMultipleEmails } from '../client'; import { EmailOptions, SendGridResponse, SendGridError, BatchSendGridResponse } from '../types'; /** * Hook for sending emails with SendGrid * @returns Object containing the send function, loading state, and error state */ export function useSendEmail(): { send: (options: EmailOptions) => Promise<SendGridResponse>; isLoading: boolean; error: SendGridError | null; response: SendGridResponse | null; reset: () => void; } { const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState<SendGridError | null>(null); const [response, setResponse] = useState<SendGridResponse | null>(null); /** * Send an email using SendGrid * @param options Email options * @returns Promise with the SendGrid response */ const send = useCallback( async (options: EmailOptions): Promise<SendGridResponse> => { setIsLoading(true); setError(null); try { const result = await sendEmail(options); setResponse(result); return result; } catch (err: any) { setError(err); throw err; } finally { setIsLoading(false); } }, [] ); const reset = useCallback(() => { setError(null); setResponse(null); }, []); return { send, isLoading, error, response, reset, }; } /** * Hook for sending multiple emails with SendGrid * @returns Object containing the send function, loading state, and error state */ export function useSendMultipleEmails(): { send: (messages: EmailOptions[]) => Promise<BatchSendGridResponse>; isLoading: boolean; error: SendGridError | null; response: BatchSendGridResponse | null; reset: () => void; } { const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState<SendGridError | null>(null); const [response, setResponse] = useState<BatchSendGridResponse | null>(null); const send = useCallback( async (messages: EmailOptions[]): Promise<BatchSendGridResponse> => { setIsLoading(true); setError(null); try { const result = await sendMultipleEmails(messages); setResponse(result); return result; } catch (err: any) { setError(err); throw err; } finally { setIsLoading(false); } }, [] ); const reset = useCallback(() => { setError(null); setResponse(null); }, []); return { send, isLoading, error, response, reset, }; }