rsnext/examples/auth0/lib/user.ts
Max Proske 55560e0c58
Convert auth0 example to TypeScript (#38087)
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>
2022-06-29 11:00:13 +00:00

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 }
}