rsnext/examples/with-passport-and-next-connect/pages/profile.js
Hoang Vo ee372f472f
feat(example): add CRUD example with next-connect and passport (#11359)
* Add with-next-connect example

* Update README

* Fix code and lint

* Fix typo

* Run prettier

* Include username

* Rename example

* Match with-passport styling

* Add comments in code

* Run prettier

* Rewrite example

* Add some comments

* Update README.md

* keys -> secret

* Updated package.json and readme

* UX changes

* Securely encrypt cookie with @hapi/iron

* Update README

* Abstract db related actions and update README

* security: add note on password hashing

* remove unused dep

* Updated readme

Co-authored-by: Luis Alvarez <luis@zeit.co>
2020-04-13 18:07:54 -05:00

89 lines
1.9 KiB
JavaScript

import { useEffect, useRef } from 'react'
import Router from 'next/router'
import { useUser } from '../lib/hooks'
function ProfileEdit() {
const [user, { mutate }] = useUser()
const nameRef = useRef()
useEffect(() => {
if (!user) return
nameRef.current.value = user.name
}, [user])
async function handleEditProfile(e) {
e.preventDefault()
const body = {
name: nameRef.current.value,
}
const res = await fetch(`/api/user`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
const updatedUser = await res.json()
mutate(updatedUser)
}
async function handleDeleteProfile() {
const res = await fetch(`/api/user`, {
method: 'DELETE',
})
if (res.status === 204) {
mutate({ user: null })
Router.replace('/')
}
}
return (
<>
<div className="form-container">
<form onSubmit={handleEditProfile}>
<label>
<span>Name</span>
<input type="text" ref={nameRef} required />
</label>
<div className="submit">
<button type="submit">Update profile</button>
<a role="button" className="delete" onClick={handleDeleteProfile}>
Delete profile
</a>
</div>
</form>
</div>
<style jsx>{`
.delete {
color: #f44336;
cursor: pointer;
}
.delete:hover {
color: #b71c1c;
}
`}</style>
</>
)
}
export default function ProfilePage() {
const [user, { loading }] = useUser()
useEffect(() => {
// redirect user to login if not authenticated
if (!loading && !user) Router.replace('/login')
}, [user, loading])
return (
<>
<h1>Profile</h1>
{user && (
<>
<p>Your profile: {JSON.stringify(user)}</p>
<ProfileEdit />
</>
)}
</>
)
}