Skip to content

Commit

Permalink
[auth] Add onIdToken. Fixes #223
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisbianca committed Nov 7, 2022
1 parent b5b2955 commit a119c2a
Show file tree
Hide file tree
Showing 2 changed files with 108 additions and 1 deletion.
69 changes: 68 additions & 1 deletion auth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { useAuthState } from 'react-firebase-hooks/auth';
List of Auth hooks:

- [useAuthState](#useauthstate)
- [useIdToken](#useidtoken)
- [useCreateUserWithEmailAndPassword](#usecreateuserwithemailandpassword)
- [useSignInWithEmailAndPassword](#usesigninwithemailandpassword)
- [useSignInWithApple](#usesigninwithapple)
Expand All @@ -35,7 +36,7 @@ List of Auth hooks:
const [user, loading, error] = useAuthState(auth, options);
```

Retrieve and monitor the authentication state from Firebase.
Retrieve and monitor the authentication state from Firebase. Uses `auth.onAuthStateChanged` so is only triggered when a user signs in or signs out. See [useIdToken](#useidtoken) if you need to monitor token changes too.

The `useAuthState` hook takes the following parameters:

Expand Down Expand Up @@ -95,6 +96,72 @@ const CurrentUser = () => {
};
```

### useIdToken

```js
const [user, loading, error] = useIdToken(auth, options);
```

Retrieve and monitor changes to the ID token from Firebase. Uses `auth.onIdTokenChanged` so includes when a user signs in, signs out or token refresh events.

The `useIdToken` hook takes the following parameters:

- `auth`: `auth.Auth` instance for the app you would like to monitor
- `options`: (optional) `Object with the following parameters:
- `onUserChanged`: (optional) function to be called with `auth.User` each time the user changes. This allows you to do things like load custom claims.

Returns:

- `user`: The `auth.UserCredential` if logged in, or `null` if not
- `loading`: A `boolean` to indicate whether the authentication state is still being loaded
- `error`: Any `AuthError` returned by Firebase when trying to load the user, or `undefined` if there is no error

#### If you are registering or signing in the user for the first time consider using [useCreateUserWithEmailAndPassword](#usecreateuserwithemailandpassword), [useSignInWithEmailAndPassword](#usesigninwithemailandpassword)

#### Full Example

```js
import { getAuth, signInWithEmailAndPassword, signOut } from 'firebase/auth';
import { useIdToken } from 'react-firebase-hooks/auth';

const auth = getAuth(firebaseApp);

const login = () => {
signInWithEmailAndPassword(auth, 'test@test.com', 'password');
};
const logout = () => {
signOut(auth);
};

const CurrentUser = () => {
const [user, loading, error] = useIdToken(auth);

if (loading) {
return (
<div>
<p>Initialising User...</p>
</div>
);
}
if (error) {
return (
<div>
<p>Error: {error}</p>
</div>
);
}
if (user) {
return (
<div>
<p>Current User: {user.user.email}</p>
<button onClick={logout}>Log out</button>
</div>
);
}
return <button onClick={login}>Log in</button>;
};
```

### useCreateUserWithEmailAndPassword

```js
Expand Down
40 changes: 40 additions & 0 deletions auth/useIdToken.ts
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];
};

0 comments on commit a119c2a

Please sign in to comment.