Skip to content

Instantly share code, notes, and snippets.

@josefaidt
Last active April 10, 2024 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josefaidt/2c87029c8ea3b6c6ced642e369f93247 to your computer and use it in GitHub Desktop.
Save josefaidt/2c87029c8ea3b6c6ced642e369f93247 to your computer and use it in GitHub Desktop.
useUserProfile hook for Amplify auth
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