rsnext/examples/with-passport/pages/signup.js
Marc 6ffc3f2a15
Updated with-passport example to fix syntax errors (#15831)
I was referencing the with-passport example and found a minor syntax error:\
The login and signup page both used `event.preventDefault()` on the submit handlers, whereby the correct reference to the event is `e` as defined within the `handleSubmit` functions.

Additionally used the chance to bump npm packages, the largest bump being swr to the latest version: 0.3.0

### Summary of all Changes made:
* Fixed syntax error on login page
* Fixed syntax error on signup page
* Bumped cookie to 0.4.1
* Bumped next-connect to 0.8.1
* Bumped swr to 0.3.0
2020-08-03 16:56:57 +00:00

62 lines
1.5 KiB
JavaScript

import { useState } from 'react'
import Router from 'next/router'
import { useUser } from '../lib/hooks'
import Layout from '../components/layout'
import Form from '../components/form'
const Signup = () => {
useUser({ redirectTo: '/', redirectIfFound: true })
const [errorMsg, setErrorMsg] = useState('')
async function handleSubmit(e) {
e.preventDefault()
if (errorMsg) setErrorMsg('')
const body = {
username: e.currentTarget.username.value,
password: e.currentTarget.password.value,
}
if (body.password !== e.currentTarget.rpassword.value) {
setErrorMsg(`The passwords don't match`)
return
}
try {
const res = await fetch('/api/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (res.status === 200) {
Router.push('/login')
} else {
throw new Error(await res.text())
}
} catch (error) {
console.error('An unexpected error happened occurred:', error)
setErrorMsg(error.message)
}
}
return (
<Layout>
<div className="login">
<Form isLogin={false} errorMessage={errorMsg} onSubmit={handleSubmit} />
</div>
<style jsx>{`
.login {
max-width: 21rem;
margin: 0 auto;
padding: 1rem;
border: 1px solid #ccc;
border-radius: 4px;
}
`}</style>
</Layout>
)
}
export default Signup