Skip to content

Instantly share code, notes, and snippets.

@blenderous
Last active December 2, 2024 09:22
Show Gist options
  • Save blenderous/2587ad9d6cedd72f5da8475af69e3b96 to your computer and use it in GitHub Desktop.
Save blenderous/2587ad9d6cedd72f5da8475af69e3b96 to your computer and use it in GitHub Desktop.
A React custom hook that calls the email sending api
import { useState } from "react";
type FormData = {
firstName: string;
lastName: string;
email: string;
message: string;
};
export function useSendEmail(): [
boolean,
boolean,
boolean,
(data: FormData) => void
] {
const [success, setSuccess] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
const apiEndpoint = "/api/email";
const handleSendEmail = async (data: FormData) => {
// set loading as true
setLoading(true);
try {
const res = await fetch(apiEndpoint, {
method: "POST",
body: JSON.stringify(data),
});
const response = await res.json();
if (response.message === "Email sent") {
setSuccess(true);
}
} catch (err) {
setSuccess(false);
setError(true);
} finally {
setLoading(false);
}
};
return [success, loading, error, handleSendEmail];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment