rsnext/examples/with-iron-session/pages/login.tsx
Vincent Voyer 942c15129c
docs(examples): Update with-iron-session to latest iron-session API (#30956)
Co-authored-by: Lee Robinson <me@leerob.io>
2021-11-09 09:30:15 -06:00

57 lines
1.5 KiB
TypeScript

import React, { useState } from 'react'
import useUser from 'lib/useUser'
import Layout from 'components/Layout'
import Form from 'components/Form'
import fetchJson, { FetchError } from 'lib/fetchJson'
export default function Login() {
// here we just check if user is already logged in and redirect to profile
const { mutateUser } = useUser({
redirectTo: '/profile-sg',
redirectIfFound: true,
})
const [errorMsg, setErrorMsg] = useState('')
return (
<Layout>
<div className="login">
<Form
errorMessage={errorMsg}
onSubmit={async function handleSubmit(event) {
event.preventDefault()
const body = {
username: event.currentTarget.username.value,
}
try {
mutateUser(
await fetchJson('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
)
} catch (error) {
if (error instanceof FetchError) {
setErrorMsg(error.data.message)
} else {
console.error('An unexpected error happened:', error)
}
}
}}
/>
</div>
<style jsx>{`
.login {
max-width: 21rem;
margin: 0 auto;
padding: 1rem;
border: 1px solid #ccc;
border-radius: 4px;
}
`}</style>
</Layout>
)
}