init
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { api } from "../lib/api";
|
||||
import type {
|
||||
LoginData,
|
||||
RegisterData,
|
||||
LoginResponse,
|
||||
RegisterResponse,
|
||||
MeResponse,
|
||||
} from "../types/auth";
|
||||
|
||||
// Query keys
|
||||
export const authKeys = {
|
||||
me: ["auth", "me"] as const,
|
||||
};
|
||||
|
||||
/**
|
||||
* Хук для получения текущего пользователя
|
||||
*/
|
||||
export function useMe() {
|
||||
return useQuery({
|
||||
queryKey: authKeys.me,
|
||||
queryFn: async () => {
|
||||
const data = await api.get("auth/me").json<MeResponse>();
|
||||
return data.user;
|
||||
},
|
||||
enabled: !!localStorage.getItem("authToken"), // Запрос только если есть токен
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Хук для логина
|
||||
*/
|
||||
export function useLogin() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (data: LoginData) => {
|
||||
const response = await api
|
||||
.post("auth/login", { json: data })
|
||||
.json<LoginResponse>();
|
||||
return response;
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
// Сохраняем токен в localStorage
|
||||
localStorage.setItem("authToken", data.session.token);
|
||||
|
||||
// Обновляем кэш текущего пользователя
|
||||
queryClient.setQueryData(authKeys.me, data.user);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Хук для регистрации
|
||||
*/
|
||||
export function useRegister() {
|
||||
return useMutation({
|
||||
mutationFn: async (data: RegisterData) => {
|
||||
const response = await api
|
||||
.post("auth/register", { json: data })
|
||||
.json<RegisterResponse>();
|
||||
return response;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Хук для логаута
|
||||
*/
|
||||
export function useLogout() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
await api.post("auth/logout").json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Удаляем токен
|
||||
localStorage.removeItem("authToken");
|
||||
|
||||
// Очищаем кэш
|
||||
queryClient.clear();
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user