Files
fast_api_template/frontend/src/hooks/useAuth.ts
T

71 lines
1.7 KiB
TypeScript
Raw Normal View History

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
2024-03-17 17:28:45 +01:00
import { useNavigate } from "@tanstack/react-router"
2024-03-08 14:58:36 +01:00
import {
2024-03-28 20:22:28 -05:00
type Body_login_login_access_token as AccessToken,
2024-03-28 21:15:11 -05:00
LoginService,
2024-04-06 18:26:12 -05:00
type UserPublic,
type UserRegister,
2024-03-28 21:15:11 -05:00
UsersService,
2025-02-17 19:55:20 +00:00
} from "@/client"
import { handleError } from "@/utils"
2025-12-07 13:21:13 +01:00
import useCustomToast from "./useCustomToast"
2024-02-29 09:47:13 -05:00
const isLoggedIn = () => {
2024-03-17 17:28:45 +01:00
return localStorage.getItem("access_token") !== null
2024-03-08 14:58:36 +01:00
}
2024-02-29 09:47:13 -05:00
const useAuth = () => {
2024-03-08 14:58:36 +01:00
const navigate = useNavigate()
const queryClient = useQueryClient()
2025-12-07 13:21:13 +01:00
const { showErrorToast } = useCustomToast()
2025-02-17 19:33:00 +00:00
const { data: user } = useQuery<UserPublic | null, Error>({
2024-04-04 16:30:42 +02:00
queryKey: ["currentUser"],
queryFn: UsersService.readUserMe,
enabled: isLoggedIn(),
})
const signUpMutation = useMutation({
mutationFn: (data: UserRegister) =>
UsersService.registerUser({ requestBody: data }),
onSuccess: () => {
navigate({ to: "/login" })
},
2025-12-07 13:21:13 +01:00
onError: handleError.bind(showErrorToast),
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["users"] })
},
})
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
}
2024-04-04 16:30:42 +02:00
const loginMutation = useMutation({
mutationFn: login,
onSuccess: () => {
navigate({ to: "/" })
},
2025-12-07 13:21:13 +01:00
onError: handleError.bind(showErrorToast),
})
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 {
signUpMutation,
loginMutation,
logout,
user,
}
}
2024-03-08 14:58:36 +01:00
export { isLoggedIn }
export default useAuth