Last active
April 10, 2024 21:53
-
-
Save josefaidt/2c87029c8ea3b6c6ced642e369f93247 to your computer and use it in GitHub Desktop.
useUserProfile hook for Amplify auth
This file contains hidden or 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
import type { PropsWithChildren } from "react" | |
import { useState, createContext, useEffect, useContext } from "react" | |
import { useAuthenticator } from "@aws-amplify/ui-react" | |
import { fetchUserAttributes } from "aws-amplify/auth" | |
type UserProfile = { | |
/** | |
* the sub | |
*/ | |
id: string | |
/** | |
* the actual email | |
*/ | |
email: string | |
/** | |
* "preferred_username" but without the alias attributes | |
*/ | |
displayName: string | |
/** | |
* whether the user is verified | |
* @default false | |
*/ | |
isVerified: boolean | |
} | |
const UserProfileContext = createContext<UserProfile | null>(null) | |
async function fetchUserProfile(): Promise<UserProfile> { | |
const attributes = await fetchUserAttributes() | |
return { | |
id: attributes.sub, | |
email: attributes.email, | |
displayName: attributes.preferred_username, | |
isVerified: attributes.email_verified, | |
} | |
} | |
export function UserProfileProvider({ children }: PropsWithChildren<{}>) { | |
const { authStatus } = useAuthenticator() | |
const [user, setUser] = useState<UserProfile | null>(null) | |
useEffect(() => { | |
if (user && authStatus === "unauthenticated") { | |
setUser(null) | |
} | |
if (!user && authStatus === "authenticated") { | |
fetchUserProfile().then(setUser) | |
} | |
}, [authStatus]) | |
return ( | |
<UserProfileContext.Provider value={user}> | |
{children} | |
</UserProfileContext.Provider> | |
) | |
} | |
export function useUserProfile() { | |
const context = useContext(UserProfileContext) | |
if (context === undefined) { | |
throw new Error("useUserProfile must be used within a UserProfileProvider") | |
} | |
return context | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment