ReactHooks
useSignIn
Perform password sign-in through the browser SimpleAuth client with local state helpers.
Overview
useSignIn wraps auth.login(). It exposes an imperative signIn function plus loading, error, and response data mirroring what your UI needs for a credential form.
Signature
export function useSignIn()Parameters
This hook takes no parameters.
Returns
| Field | Type | Description |
|---|---|---|
signIn | (input: { email: string; password: string }) => Promise<LoginResponse> | Calls auth.login and updates local state. |
data | LoginResponse | null | Last successful login response. |
error | string | null | Human-readable error string when login fails. |
isError | boolean | Convenience flag derived from error. |
isLoading | boolean | True while a login request is running. |
reset | () => void | Clears local hook state. |
Example
"use client"
import { useSignIn } from "@/components/simpleauth"
export function EmailPasswordLogin() {
const { signIn, isLoading, error } = useSignIn()
async function onSubmit(formData: FormData) {
const email = String(formData.get("email") ?? "")
const password = String(formData.get("password") ?? "")
await signIn({ email, password })
}
return (
<form action={async (fd) => onSubmit(fd)}>
<input name="email" type="email" required />
<input name="password" type="password" required />
{error ? <p>{error}</p> : null}
<button type="submit" disabled={isLoading}>
{isLoading ? "Signing in…" : "Sign in"}
</button>
</form>
)
}How it works
- Pulls the browser client from context via
useSimpleAuthClient. - Maps thrown
SimpleAuthErrorinstances (and genericError) into theerrorstring. - Keeps
isLoadingaccurate around theloginpromise.
Shipped by
npx @simpleauthjs/react add sign-inSource
components/simpleauth/hooks/use-sign-in.ts
"use client"
import { useState } from "react"
import { SimpleAuthError, type LoginResponse } from "@simpleauthjs/core"
import { useSimpleAuthClient } from "../provider"
type SignInInput = {
email: string
password: string
}
function getErrorMessage(error: unknown) {
if (error instanceof SimpleAuthError) {
return error.message
}
if (error instanceof Error) {
return error.message
}
return "Unable to sign in."
}
export function useSignIn() {
const auth = useSimpleAuthClient()
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [data, setData] = useState<LoginResponse | null>(null)
async function signIn(input: SignInInput) {
setIsLoading(true)
setError(null)
try {
const response = await auth.login(input)
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 {
signIn,
data,
error,
isError: Boolean(error),
isLoading,
reset,
}
}