diff --git a/docs/guide/auth.md b/docs/guide/auth.md index 4ec3fef6..5156ea0f 100644 --- a/docs/guide/auth.md +++ b/docs/guide/auth.md @@ -48,6 +48,8 @@ const user = useCurrentUser() ### Wait for the user to be loaded +The `useCurrentUser()` composable will give you an `undefined` value until the user is loaded. It will then become `null` or the user object itself. If you need to wait for the user to be loaded in a declarative fashion, you can use the `useIsCurrentUserLoaded()` composable. Internally it's just a computed property that returns `true` when if user is not `undefined`. + There is also a `getCurrentUser()` function that returns a promise of the current user. This is useful if you want to wait for the user to be loaded before doing anything. You can, for example, await it within a navigation guard: ```ts diff --git a/src/auth/index.ts b/src/auth/index.ts index fb33e667..d63b60f7 100644 --- a/src/auth/index.ts +++ b/src/auth/index.ts @@ -8,6 +8,7 @@ import { authUserMap, setupOnAuthStateChanged } from './user' export { useCurrentUser, + useIsCurrentUserLoaded, getCurrentUser, updateCurrentUserProfile, updateCurrentUserEmail, diff --git a/src/auth/user.ts b/src/auth/user.ts index 0e3824af..d01308d6 100644 --- a/src/auth/user.ts +++ b/src/auth/user.ts @@ -8,7 +8,7 @@ import { reauthenticateWithCredential, AuthCredential, } from 'firebase/auth' -import type { Ref } from 'vue-demi' +import { computed, Ref } from 'vue-demi' import { useFirebaseApp } from '../app' import type { _MaybeRef, _Nullable } from '../shared' @@ -36,6 +36,17 @@ export function useCurrentUser(name?: string) { return authUserMap.get(useFirebaseApp(name))! } +/** + * Helper that returns a computed boolean that becomes `true` as soon as the current user is no longer `undefined`. Note + * this doesn't ensure the user is logged in, only if the initial signing process has run. + * + * @param name - name of the application + */ +export function useIsCurrentUserLoaded(name?: string) { + const currentUser = useCurrentUser(name) + return computed(() => currentUser !== undefined) +} + /** * Updates the current user profile and updates the current user state. This function internally calls `updateProfile()` * from 'firebase/auth' and then updates the current user state. diff --git a/src/index.ts b/src/index.ts index c93d50da..ef06c16f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -78,6 +78,7 @@ export { useFirebaseApp } from './app' */ export { useCurrentUser, + useIsCurrentUserLoaded, VueFireAuth, useFirebaseAuth, getCurrentUser,