useForgotPassword
The useForgotPassword hook provides methods for handling password reset flows including sending OTP codes and resetting passwords.
Return Value
Whether a password reset operation is in progress
Show Initiates the password reset flow by sending an OTP to the user's email
Result indicating success or error
Show Verifies the OTP code sent to the user's email
Result containing the reset token on success
Show Resets the user's password using the token from OTP verification
The reset token from OTP verification
Result containing the session on success
import { useForgotPassword } from "@wacht/react-router";
function ForgotPasswordPage() {
const { loading, forgotPassword, verifyOtp, resetPassword } = useForgotPassword();
const [step, setStep] = useState<"email" | "otp" | "done">("email");
const [email, setEmail] = useState("");
const [token, setToken] = useState("");
const handleSendCode = async () => {
const result = await forgotPassword(email);
if (result.data) {
setStep("otp");
}
};
const handleVerifyOtp = async (otp: string) => {
const result = await verifyOtp(email, otp);
if (result.data?.token) {
setToken(result.data.token);
setStep("done");
}
};
const handleReset = async (newPassword: string) => {
const result = await resetPassword(token, newPassword);
if (result.data) {
setStep("done");
}
};
return (
<div>
{step === "email" && (
<form onSubmit={() => handleSendCode()}>
<input
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter your email"
/>
<button disabled={loading}>Send Reset Code</button>
</form>
)}
{step === "otp" && (
<form onSubmit={(e) => {
e.preventDefault();
handleVerifyOtp("123456");
}}>
<input placeholder="Enter OTP code" />
<button disabled={loading}>Verify</button>
</form>
)}
{step === "done" && <p>Password reset successfully!</p>}
</div>
);
}
Examples
Initiate Password Reset
const { forgotPassword } = useForgotPassword();
const result = await forgotPassword("user@example.com");
// Returns success if OTP was sent
// result.data?: {}
// result.error?: ErrorInterface
Verify OTP
const { verifyOtp } = useForgotPassword();
const result = await verifyOtp("user@example.com", "123456");
// result.data?: { token: string }
// result.error?: ErrorInterface
Reset Password
const { resetPassword } = useForgotPassword();
const result = await resetPassword("token_from_otp", "NewSecurePassword123!");
// result.data?: Session
// result.error?: ErrorInterface
Complete Flow
- User enters email address
- Call
forgotPassword(email) to send OTP
- User enters OTP code
- Call
verifyOtp(email, otp) to get reset token
- User enters new password
- Call
resetPassword(token, newPassword) to complete reset