| San3yuan | 6f2ed69 | 2025-04-16 20:24:49 +0800 | [diff] [blame] | 1 | import React, { useEffect } from 'react'; |
| 2 | import { useApi } from '@/hooks/request'; |
| 3 | import request from '@/utils/request'; |
| 4 | import { postUserLogin} from '@/api/auth'; |
| 5 | import { useAppDispatch } from '@/hooks/store'; |
| 6 | import { RootState } from '@/store'; |
| 7 | import style from './login.module.css'; |
| 8 | import { useState } from 'react'; |
| 9 | import { useSelector } from 'react-redux'; |
| 10 | import { useNavigate } from 'react-router'; |
| 11 | import logo from '&/asserts/logo.png'; |
| 12 | import { getUserInfo } from '@/api/user'; |
| 13 | |
| 14 | |
| 15 | const Login: React.FC = () => { |
| 16 | const [email, setEmail] = useState(''); |
| 17 | const [password, setPassword] = useState(''); |
| 18 | const dispatch = useAppDispatch(); |
| 19 | const { refresh: postUserLoginRefresh } = useApi(() => request.post(postUserLogin, {}), false); |
| 20 | const { refresh: getUserInfoRefresh } = useApi(async () => await request.get(getUserInfo), false); |
| 21 | |
| 22 | const nav = useNavigate(); |
| 23 | const handleLogin = async () => { |
| 24 | try { |
| 25 | const res = await postUserLoginRefresh(); |
| 26 | if (res==null ||(res as any).error) { |
| 27 | alert('Login failed. Please check your credentials.'); |
| 28 | return; |
| 29 | } |
| 30 | dispatch({ type: "user/login", payload: res }); |
| 31 | |
| 32 | const userInfo = await getUserInfoRefresh(); |
| 33 | if (userInfo==null || (userInfo as any).error) { |
| 34 | alert('Failed to fetch user information.'); |
| 35 | return; |
| 36 | } |
| 37 | dispatch({ type: "user/getUserInfo", payload: userInfo }); |
| 38 | nav('/'); |
| 39 | } catch (error) { |
| 40 | alert('An unexpected error occurred. Please try again later.'); |
| 41 | if (error instanceof Error) { |
| 42 | console.error(error.message); // 明确访问 message 属性 |
| 43 | } else { |
| 44 | console.error('Unknown error occurred'); |
| 45 | } |
| 46 | } |
| 47 | }; |
| 48 | |
| 49 | return ( |
| 50 | <div className={style.form}> |
| 51 | <img className={style.logo} src={logo} alt="logo"></img> |
| 52 | <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} className={style.email} placeholder="Enter your email" /> |
| 53 | <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} className={style.password} placeholder="Enter your password" /> |
| 54 | <button className={style.submit} onClick={handleLogin}>登录</button> |
| 55 | <button className={style.register}>注册</button> |
| 56 | <button className={style.forget}> 忘记密码</button> |
| 57 | </div> |
| 58 | ); |
| 59 | }; |
| 60 | |
| 61 | export default Login; |