Last active
October 22, 2022 21:27
-
-
Save itwasmattgregg/b62e842aae5d71849675e322f88c9f53 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from 'react'; | |
import useUser from '@utils/useUser'; | |
export default function Login() { | |
// here we just check if user is already logged in and redirect to admin | |
const { mutateUser } = useUser({ | |
redirectTo: '/admin', | |
redirectIfFound: true, | |
}); | |
const [errorMsg, setErrorMsg] = useState(''); | |
async function handleSubmit(e) { | |
e.preventDefault(); | |
const body = { | |
password: e.currentTarget.password.value, | |
}; | |
const userData = await fetch('/api/login', { | |
method: 'POST', | |
headers: { 'Content-Type': 'application/json' }, | |
body: JSON.stringify(body), | |
}); | |
const user = await userData.json(); | |
try { | |
await mutateUser(user); | |
} catch (error) { | |
console.error('An unexpected error happened:', error); | |
setErrorMsg(error.data.message); | |
} | |
} | |
return ( | |
<form onSubmit={handleSubmit}> | |
<label> | |
Enter password | |
<input type='password' name='password' required /> | |
</label> | |
<button type='submit'>Login</button> | |
{errorMsg && <p>{errorMsg}</p>} | |
</form> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment