55560e0c58
Converted auth0 example over to TypeScript to match the Contribution guidelines, and got rid of the `tslib` dependency. Note: You must copy `.env.local.example` to `.env.local`, or you will encounter "TypeError: "secret" is required" at build time. ## Documentation / Examples - [X] Make sure the linting passes by running `pnpm lint` - [X] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples) Co-authored-by: Balázs Orbán <18369201+balazsorban44@users.noreply.github.com>
76 lines
1.5 KiB
TypeScript
76 lines
1.5 KiB
TypeScript
import { UserProfile } from '@auth0/nextjs-auth0'
|
|
import { useState, useEffect } from 'react'
|
|
|
|
export async function fetchUser(cookie = '') {
|
|
if (typeof window !== 'undefined' && window.__user) {
|
|
return window.__user
|
|
}
|
|
|
|
const res = await fetch(
|
|
'/api/me',
|
|
cookie
|
|
? {
|
|
headers: {
|
|
cookie,
|
|
},
|
|
}
|
|
: {}
|
|
)
|
|
|
|
if (!res.ok) {
|
|
delete window.__user
|
|
return null
|
|
}
|
|
|
|
const json: UserProfile = await res.json()
|
|
if (typeof window !== 'undefined') {
|
|
window.__user = json
|
|
}
|
|
return json
|
|
}
|
|
|
|
export function useFetchUser(
|
|
{ required }: { required: boolean } = { required: false }
|
|
) {
|
|
const [loading, setLoading] = useState(
|
|
() => !(typeof window !== 'undefined' && window.__user)
|
|
)
|
|
const [user, setUser] = useState(() => {
|
|
if (typeof window === 'undefined') {
|
|
return null
|
|
}
|
|
|
|
return window.__user || null
|
|
})
|
|
|
|
useEffect(
|
|
() => {
|
|
if (!loading && user) {
|
|
return
|
|
}
|
|
setLoading(true)
|
|
let isMounted = true
|
|
|
|
fetchUser().then((user) => {
|
|
// Only set the user if the component is still mounted
|
|
if (isMounted) {
|
|
// When the user is not logged in but login is required
|
|
if (required && !user) {
|
|
window.location.href = '/api/login'
|
|
return
|
|
}
|
|
setUser(user)
|
|
setLoading(false)
|
|
}
|
|
})
|
|
|
|
return () => {
|
|
isMounted = false
|
|
}
|
|
},
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
[]
|
|
)
|
|
|
|
return { user, loading }
|
|
}
|