Files
full-stack-fastapi-template/frontend/src/hooks/useAuth.ts

71 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-04-08 15:49:22 -05:00
import { useMutation, useQuery } from "@tanstack/react-query"
2024-03-17 17:28:45 +01:00
import { useNavigate } from "@tanstack/react-router"
import { useState } from "react"
import { AxiosError } from "axios"
2024-03-08 14:58:36 +01:00
import {
type Body_login_login_access_token as AccessToken,
type ApiError,
2024-03-28 21:15:11 -05:00
LoginService,
type UserPublic,
2024-03-28 21:15:11 -05:00
UsersService,
2024-03-17 17:28:45 +01:00
} from "../client"
const isLoggedIn = () => {
2024-03-17 17:28:45 +01:00
return localStorage.getItem("access_token") !== null
2024-03-08 14:58:36 +01:00
}
const useAuth = () => {
const [error, setError] = useState<string | null>(null)
2024-03-08 14:58:36 +01:00
const navigate = useNavigate()
const { data: user, isLoading } = useQuery<UserPublic | null, Error>({
queryKey: ["currentUser"],
queryFn: UsersService.readUserMe,
enabled: isLoggedIn(),
})
2024-03-08 14:58:36 +01:00
const login = async (data: AccessToken) => {
const response = await LoginService.loginAccessToken({
formData: data,
})
2024-03-17 17:28:45 +01:00
localStorage.setItem("access_token", response.access_token)
2024-03-08 14:58:36 +01:00
}
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)
},
})
2024-03-08 14:58:36 +01:00
const logout = () => {
2024-03-17 17:28:45 +01:00
localStorage.removeItem("access_token")
navigate({ to: "/login" })
2024-03-08 14:58:36 +01:00
}
return {
loginMutation,
logout,
user,
isLoading,
error,
2024-04-09 16:12:19 +02:00
resetError: () => setError(null),
}
}
2024-03-08 14:58:36 +01:00
export { isLoggedIn }
export default useAuth