forked from danvitoriano/nextjs-auth0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.js
73 lines (63 loc) · 1.44 KB
/
user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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 = await res.json()
if (typeof window !== 'undefined') {
window.__user = json
}
return json
}
export function useFetchUser({ required } = {}) {
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 }
}