useSWR
This commit is contained in:
@ -1,17 +1,32 @@
|
||||
import {useState,useContext} from 'react';
|
||||
import {useState} from 'react';
|
||||
import useSWR from 'swr';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import './Login.css';
|
||||
import {loginUser} from '../services/PhpApi'
|
||||
import {getUser, loginUser} from '../services/PhpApi'
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { TUser } from '../context/UserContext';
|
||||
|
||||
const Login = () =>
|
||||
{
|
||||
const [redirect, setRedirect] = useState("false");
|
||||
const [formData, setFormData] = useState({
|
||||
email:'',
|
||||
password:''
|
||||
});
|
||||
|
||||
const {data, error, isLoading, mutate} = useSWR('Login', getUser);
|
||||
const navigate = useNavigate();
|
||||
|
||||
if (error) return (<div>failed to load</div>);
|
||||
if (isLoading) return (<div>loading...</div>);
|
||||
|
||||
|
||||
let user: TUser | null;
|
||||
if(data.success)
|
||||
{
|
||||
user = data.user;
|
||||
formData.email = user!.email;
|
||||
}
|
||||
|
||||
const onChangeInput = (e: React.FormEvent<HTMLInputElement>) =>
|
||||
{
|
||||
if(e.currentTarget.type === 'email' || e.currentTarget.type === 'password')
|
||||
@ -29,20 +44,10 @@ const Login = () =>
|
||||
|
||||
if(!Object.values(formData).every(val => val.trim() !== ''))
|
||||
{
|
||||
setErrMsg('Please Fill in all Required Fields!');
|
||||
toast.error('Please Fill in all Required Fields!');
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await loginUser(formData);
|
||||
if(data.success)
|
||||
{
|
||||
setRedirect('Redirecting...');
|
||||
setErrMsg(data.message!);
|
||||
await getUser();
|
||||
navigate('/profil');
|
||||
return;
|
||||
}
|
||||
setErrMsg(data.message!);
|
||||
mutate(loginUser, formData)
|
||||
}
|
||||
|
||||
return (
|
||||
@ -64,8 +69,7 @@ const Login = () =>
|
||||
<label htmlFor="password">Password:</label>
|
||||
<input type="password" name="password" onChange={onChangeInput} placeholder="New password" id="password" value={formData.password} required />
|
||||
</div>
|
||||
{errMsg !== "false" && <div className="err-msg">{errMsg}</div>}
|
||||
{redirect !== "false" ? redirect : <button type="submit" disabled={wait}>Login</button>}
|
||||
<button type="submit">Login</button>
|
||||
<div className="bottom-link"><Link to="/reg">Register</Link></div>
|
||||
</form> }
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user