Skip to content

add options to useAuthState hook "onUserChanged" #139

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 4, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions auth/useAuthState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,28 @@ import { LoadingHook, useLoadingValue } from '../util';

export type AuthStateHook = LoadingHook<User | null, Error>;

export default (auth: Auth): AuthStateHook => {
export default (auth: firebase.auth.Auth, options: {onUserChanged?: (user?: firebase.User) => Promise<void>}): AuthStateHook => {
const { error, loading, setError, setValue, value } = useLoadingValue<
User | null,
Error
>(() => auth.currentUser);

useEffect(() => {
return onAuthStateChanged(auth, setValue, setError);
const listener = auth.onAuthStateChanged(async (user) => {
if(typeof options?.onUserChanged === 'function') {
// onUserLoaded function to process custom claims on any other trigger function
try {
await options.onUserChanged(user)
} catch(e) {
setError(e)
}
}
setValue(user);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will never be executed if the passed handler fails. It should be considered to set the value first and then perform the handler.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mauriceackel or should it be wrapped in try .. catch ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively it could be mentioned that the onUserChanged should handle errors within that function.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This definitely needs some error handling built in, otherwise it will be very difficult to debug any issues. I'd propose a try / catch, then re-using setError

}, setError);

return () => {
listener();
};
}, [auth]);

const resArray: AuthStateHook = [value, loading, error];
Expand Down