-
-
Notifications
You must be signed in to change notification settings - Fork 6k
/
Copy pathuseAuth.ts
103 lines (88 loc) · 2.44 KB
/
useAuth.ts
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { useNavigate } from "@tanstack/react-router"
import { useState } from "react"
import { AxiosError } from "axios"
import {
type Body_login_login_access_token as AccessToken,
type ApiError,
LoginService,
type UserPublic,
type UserRegister,
UsersService,
} from "../client"
import useCustomToast from "./useCustomToast"
const isLoggedIn = () => {
return localStorage.getItem("access_token") !== null
}
const useAuth = () => {
const [errorSetter, setError] = useState<string | null>(null)
const navigate = useNavigate()
const showToast = useCustomToast()
const queryClient = useQueryClient()
const { data: user, isLoading, error, errorUpdateCount } = useQuery<UserPublic | null, Error>({
queryKey: ["currentUser"],
queryFn: UsersService.readUserMe,
enabled: isLoggedIn(),
})
const signUpMutation = useMutation({
mutationFn: (data: UserRegister) =>
UsersService.registerUser({ requestBody: data }),
onSuccess: () => {
navigate({ to: "/login" })
showToast(
"Account created.",
"Your account has been created successfully.",
"success",
)
},
onError: (err: ApiError) => {
let errDetail = (err.body as any)?.detail
if (err instanceof AxiosError) {
errDetail = err.message
}
showToast("Something went wrong.", errDetail, "error")
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["users"] })
},
})
const login = async (data: AccessToken) => {
const response = await LoginService.loginAccessToken({
formData: data,
})
localStorage.setItem("access_token", response.access_token)
}
const loginMutation = useMutation({
mutationFn: login,
onSuccess: () => {
navigate({ to: "/" })
},
onError: (err: ApiError) => {
let errDetail = (err.body as any)?.detail
if (err instanceof AxiosError) {
errDetail = err.message
}
if (Array.isArray(errDetail)) {
errDetail = "Something went wrong"
}
setError(errDetail)
},
})
const logout = () => {
localStorage.removeItem("access_token")
navigate({ to: "/login" })
}
return {
signUpMutation,
loginMutation,
logout,
user,
isLoading,
errorSetter,
error,
errorUpdateCount,
resetError: () => setError(null),
}
}
export { isLoggedIn }
export default useAuth