-
Notifications
You must be signed in to change notification settings - Fork 304
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b5b2955
commit a119c2a
Showing
2 changed files
with
108 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 |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { Auth, onIdTokenChanged, User } from 'firebase/auth'; | ||
import { useEffect } from 'react'; | ||
import { LoadingHook, useLoadingValue } from '../util/dist/util'; | ||
|
||
export type IdTokenHook = LoadingHook<User | null, Error>; | ||
|
||
type IdTokenOptions = { | ||
onUserChanged?: (user: User | null) => Promise<void>; | ||
}; | ||
|
||
export default (auth: Auth, options?: IdTokenOptions): IdTokenHook => { | ||
const { error, loading, setError, setValue, value } = useLoadingValue< | ||
User | null, | ||
Error | ||
>(() => auth.currentUser); | ||
|
||
useEffect(() => { | ||
const listener = onIdTokenChanged( | ||
auth, | ||
async (user) => { | ||
if (options?.onUserChanged) { | ||
// onUserChanged function to process custom claims on any other trigger function | ||
try { | ||
await options.onUserChanged(user); | ||
} catch (e) { | ||
setError(e as Error); | ||
} | ||
} | ||
setValue(user); | ||
}, | ||
setError | ||
); | ||
|
||
return () => { | ||
listener(); | ||
}; | ||
}, [auth]); | ||
|
||
return [value, loading, error]; | ||
}; |