Удален AuthContext, логика авторизации перенесена в Redux. Добавлены authSlice и authApi для управления состоянием авторизации.
36 lines
1.2 KiB
JavaScript
36 lines
1.2 KiB
JavaScript
import { useDispatch } from "react-redux";
|
||
import { notification } from "antd";
|
||
import {setError, setUser} from "../../../Redux/Slices/authSlice.js";
|
||
import {useLoginMutation} from "../../../Api/authApi.js";
|
||
|
||
const useLoginPage = () => {
|
||
const dispatch = useDispatch();
|
||
const [loginUser, { isLoading }] = useLoginMutation();
|
||
|
||
const onFinish = async (loginData) => {
|
||
try {
|
||
const response = await loginUser(loginData).unwrap();
|
||
const token = response.access_token || response.token;
|
||
if (!token) {
|
||
throw new Error("Токен не получен от сервера");
|
||
}
|
||
localStorage.setItem("access_token", token);
|
||
dispatch(setUser({ token }));
|
||
} catch (error) {
|
||
const errorMessage = error?.data?.message || "Не удалось войти";
|
||
dispatch(setError(errorMessage));
|
||
notification.error({
|
||
message: "Ошибка при входе",
|
||
description: errorMessage,
|
||
placement: "topRight",
|
||
});
|
||
}
|
||
};
|
||
|
||
return {
|
||
onFinish,
|
||
isLoading,
|
||
};
|
||
};
|
||
|
||
export default useLoginPage; |