ReactHooks
useForgotPassword
Send a password reset email through the browser client.
Overview
useForgotPassword wraps auth.forgotPassword({ email }) with loading, success, and error state.
Signature
export function useForgotPassword()Parameters
This hook takes no parameters.
Returns
| Field | Type | Description |
|---|---|---|
forgotPassword | (email: string) => Promise<unknown> | Sends the reset email for the trimmed address. |
data | unknown | Last successful API payload when present. |
error | string | null | Human-readable error when the request fails. |
isError | boolean | Convenience flag from error. |
isLoading | boolean | True while the forgot-password request runs. |
isSuccess | boolean | True after a response with success from the API. |
reset | () => void | Clears hook state. |
Example
"use client"
import { useForgotPassword } from "@/components/simpleauth"
export function ForgotLink() {
const { forgotPassword, isLoading, error, isSuccess } = useForgotPassword()
async function send() {
await forgotPassword("user@example.com")
}
return (
<div>
<button type="button" onClick={send} disabled={isLoading}>
Email reset link
</button>
{error ? <p>{error}</p> : null}
{isSuccess ? <p>If an account exists, check your inbox.</p> : null}
</div>
)
}How it works
- Uses
useSimpleAuthClient()and mapsSimpleAuthError(andError) intoerror.
Shipped by
npx @simpleauthjs/react add forgot-passwordSource
components/simpleauth/hooks/use-forgot-password.ts
"use client"
import { useState } from "react"
import { SimpleAuthError, type SuccessResponse } from "@simpleauthjs/core"
import { useSimpleAuthClient } from "../provider"
function getErrorMessage(error: unknown) {
if (error instanceof SimpleAuthError) {
return error.message
}
if (error instanceof Error) {
return error.message
}
return "Unable to send reset email."
}
export function useForgotPassword() {
const auth = useSimpleAuthClient()
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [data, setData] = useState<SuccessResponse | null>(null)
async function forgotPassword(email: string) {
setIsLoading(true)
setError(null)
try {
const response = await auth.forgotPassword({ email: email.trim() })
setData(response)
return response
} catch (requestError) {
setData(null)
setError(getErrorMessage(requestError))
throw requestError
} finally {
setIsLoading(false)
}
}
function reset() {
setData(null)
setError(null)
setIsLoading(false)
}
return {
forgotPassword,
data,
error,
isError: Boolean(error),
isLoading,
isSuccess: Boolean(data?.success),
reset,
}
}