SimpleAuth
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

FieldTypeDescription
forgotPassword(email: string) => Promise<unknown>Sends the reset email for the trimmed address.
dataunknownLast successful API payload when present.
errorstring | nullHuman-readable error when the request fails.
isErrorbooleanConvenience flag from error.
isLoadingbooleanTrue while the forgot-password request runs.
isSuccessbooleanTrue after a response with success from the API.
reset() => voidClears 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 maps SimpleAuthError (and Error) into error.

Shipped by

npx @simpleauthjs/react add forgot-password

Source

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,
  }
}

On this page