Skip to content

useAuth

Category
Export Size
318 B
Package
@reause/firebase
Last Changed
5 days ago

Reactive Firebase Auth binding. It provides a controllable user state and isAuthenticated flag so you can easily react to changes in the users' authentication status.

Usage

tsx
import { 
useAuth
} from '@reause/firebase'
import {
initializeApp
} from 'firebase/app'
import {
getAuth
,
GoogleAuthProvider
,
signInWithPopup
} from 'firebase/auth'
const
app
=
initializeApp
({ /* config */ })
const
auth
=
getAuth
(
app
)
function
Profile
() {
// 1. 直接传入 auth 实例 const {
isAuthenticated
,
user
,
loading
,
error
} =
useAuth
(
auth
)
if (
loading
)
return <
div
>Loading...</div>
if (
error
)
return <
div
>{`Auth error: ${
error
.
message
}`}</div>
if (!isAuthenticated) return <
div
>Please log in</div>
return <
div
>{`Welcome, ${user?.displayName}`}</div>
} const
signIn
= () =>
signInWithPopup
(
auth
, new
GoogleAuthProvider
())

Return Values

NameTypeDescription
userUser | nullThe current Firebase user, or null if not authenticated
isAuthenticatedbooleanWhether a user is currently authenticated
loadingbooleanWhether the auth state is still being resolved — true until onIdTokenChanged reports the state
errorError | nullThe error thrown while subscribing to onIdTokenChanged, or null

The hook automatically updates when the user's ID token changes (including sign-in, sign-out, and token refresh events) using Firebase's onIdTokenChanged listener.

Type Declarations

ts
export interface UseAuthOptions {
    errorHandler?: (err: Error) => void;
}

export interface UseAuthReturn {
    isAuthenticated: boolean;
    user: User | null;
    loading: boolean;
    error: Error | null;
}

export function useAuth(auth: Auth, options?: UseAuthOptions): UseAuthReturn

Source

Source

Contributors

hairyf

Changelog

v0.1.0 on
04bfb - feat(firebase): implement useAuth (#80)

Released under the MIT License. v0.1.8