Last active
December 2, 2024 09:22
-
-
Save blenderous/2587ad9d6cedd72f5da8475af69e3b96 to your computer and use it in GitHub Desktop.
A React custom hook that calls the email sending api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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