-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(auth): add useAuthIdToken (#156)
- Loading branch information
1 parent
0abc13f
commit f351734
Showing
3 changed files
with
59 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
export * from "./useAuthIdToken.js"; | ||
export * from "./useAuthState.js"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { Auth, AuthError, getIdToken, onIdTokenChanged } from "firebase/auth"; | ||
import { useCallback } from "react"; | ||
import { ValueHookResult } from "../common/index.js"; | ||
import { useListen, UseListenOnChange } from "../internal/useListen.js"; | ||
import { LoadingState } from "../internal/useLoadingValue.js"; | ||
|
||
export type UseAuthIdTokenResult = ValueHookResult<string | null, AuthError>; | ||
|
||
/** | ||
* Returns and updates the JWT of the currently authenticated user | ||
* | ||
* @param {Auth} auth Firebase Auth instance | ||
* @returns {UseAuthIdTokenResult} JWT, loading state, and error | ||
* * value: JWT; `undefined` if the JWT is currently being fetched, or an error occurred | ||
* * loading: `true` while fetching the JWT; `false` if the JWT was fetched successfully or an error occurred | ||
* * error: `undefined` if no error occurred | ||
*/ | ||
export function useAuthIdToken(auth: Auth): UseAuthIdTokenResult { | ||
const onChange: UseListenOnChange<string | null, AuthError, Auth> = useCallback( | ||
(stableAuth, next, error) => | ||
onIdTokenChanged(stableAuth, async (user) => { | ||
if (user) { | ||
try { | ||
// Can also be accessed via `user.accessToken`, but that's not officially documented | ||
const idToken = await getIdToken(user); | ||
next(idToken); | ||
} catch (e) { | ||
error(e as AuthError); | ||
} | ||
} else { | ||
next(null); | ||
} | ||
}), | ||
[] | ||
); | ||
|
||
return useListen(auth, onChange, () => true, LoadingState); | ||
} |