LocChat/client/components/sign_in/_sign_in.jsx

60 lines
1.7 KiB
React
Raw Normal View History

2021-11-22 16:21:53 -05:00
import { useContext, useState } from 'react';
2021-11-20 21:34:10 -05:00
import { useNavigate } from 'react-router';
2021-11-23 16:04:12 -05:00
import { AuthContext } from '../../utils/auth_context';
import { Paper } from '../common/paper';
import { Input } from '../common/input';
import { Button } from '../common/button';
2021-11-20 21:34:10 -05:00
2021-11-20 20:18:58 -05:00
export const SignIn = () => {
2021-11-23 16:04:12 -05:00
const [, setAuthToken] = useContext(AuthContext);
2021-11-20 21:34:10 -05:00
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const navigate = useNavigate();
const goToSignUp = () => {
navigate('/signup');
};
2021-11-22 16:21:53 -05:00
const signIn = async () => {
const res = await fetch('/sessions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email,
password,
}),
});
if (res.status === 201) {
const result = await res.json();
2021-11-23 16:04:12 -05:00
setAuthToken(result.token);
2021-11-22 16:21:53 -05:00
navigate('/');
} else {
console.error('An issue occurred when logging in.');
}
};
2021-11-20 21:34:10 -05:00
return (
2021-11-23 16:04:12 -05:00
<div className="flex flex-row justify-center m-4">
<div className="w-96">
<Paper>
<div>Email</div>
<Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<div>Password</div>
<Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
<div className="flex flex-row justify-end mt-2">
<Button type="button" onClick={goToSignUp}>
Sign up
</Button>
<div className="pl-2" />
<Button type="button" onClick={signIn}>
Sign in
</Button>
</div>
</Paper>
2021-11-20 21:34:10 -05:00
</div>
</div>
);
2021-11-20 20:18:58 -05:00
};