How create custom hook for login/register with e.preventDefault()

I want create custom hook for login and register functions because its best practice DRY (don't repeat yourself) I use the same function in /login and in AuthModal.tsx Here is my function for register
async function register(e: React.FormEvent) {
e.preventDefault()
if (email && password) {
try {
const response = await supabase.auth.signUp({ email: email, password: password })
if (response.error) throw response.error

if (response.data.user?.id) {
const { error } = await supabase
.from("users")
.insert({ id: response.data.user.id, username: username, email: email })
if (error) throw error

userStore.authUser(response.data.user.id)
setSuccess("Check your email")
}
} catch (error) {
console.error("register - ", error)
setError("Error")
}
}
}
async function register(e: React.FormEvent) {
e.preventDefault()
if (email && password) {
try {
const response = await supabase.auth.signUp({ email: email, password: password })
if (response.error) throw response.error

if (response.data.user?.id) {
const { error } = await supabase
.from("users")
.insert({ id: response.data.user.id, username: username, email: email })
if (error) throw error

userStore.authUser(response.data.user.id)
setSuccess("Check your email")
}
} catch (error) {
console.error("register - ", error)
setError("Error")
}
}
}
How do I create custom hook for it - when I tried do this I got an error that tells me that I need 3 arguments instead of 2 (it was login and password but it requires also e) that uses for e.preventDefault() I have this form
<form className="flex flex-col gap-y-2" onSubmit={authAction === "Login" ? login : register}>
<Button type="submit">Login</Button>
</form>
<form className="flex flex-col gap-y-2" onSubmit={authAction === "Login" ? login : register}>
<Button type="submit">Login</Button>
</form>
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server