Skip to content

Commit

Permalink
created api and endpoint for updating user information, not working
Browse files Browse the repository at this point in the history
  • Loading branch information
AronGunnar committed Feb 6, 2024
1 parent 9adb213 commit b9e506c
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 61 deletions.
9 changes: 6 additions & 3 deletions src/components/Profile/scans.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ export default function Scans({ scans }) {
</div>
<table className='my-8 w-[100%] text-left'>
<thead>
<tr className='text-gray-700'>
<th className='border-b-1 p-[8px]'>Product</th>
<tr className='border-b-[1px] text-gray-700'>
<th>Product</th>
<th>Product ID</th>
<th>Date Scanned</th>
<th></th>
Expand All @@ -42,7 +42,10 @@ export default function Scans({ scans }) {
<tbody>
{scans ? (
scans.map(scan => (
<tr key={scan._id} className='text-gray-700 hover:bg-[#0f8a8086]'>
<tr
key={scan._id}
className='border-b-[1px] text-gray-700 hover:bg-[#0f8a8086]'
>
<td>{scan.product.name}</td>
<td>{scan.product._id}</td>
<td>{formatDate(scan.createdAt)}</td>
Expand Down
134 changes: 88 additions & 46 deletions src/components/Profile/settings.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,45 @@
import { PencilIcon } from '@heroicons/react/24/outline'
import ReactModal from 'react-modal'
import { useState } from 'react'

export default function Settings({ user, userid }) {
// State variables to manage edit mode for each form field
const [editMode, setEditMode] = useState(false)
const [editedName, setEditedName] = useState(user.name)
const [editedEmail, setEditedEmail] = useState(user.email)
const [editedPassword, setEditedPassword] = useState('')
const [editedCompany, setEditedCompany] = useState('')

// Function to handle form submission
const handleSubmit = editModeSetter => {
// Make an API call to update user information
fetch(`/api/v1/users/me/${userid}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: editedName,
email: editedEmail,
}),
})
.then(response => {
if (response.ok) {
console.log('User information updated successfully')
// Handle any UI updates or notifications indicating success
} else {
console.error('Failed to update user information')
// Handle error scenario
}
})
.catch(error => {
console.error('Error updating user information:', error)
})
.finally(() => {
// Always reset edit mode regardless of success or failure
editModeSetter(false)
})
}

export default function Settings({ user }) {
return (
<div className=''>
<div>
Expand All @@ -22,21 +60,18 @@ export default function Settings({ user }) {
<form className='flex flex-row justify-between sm:col-span-1 sm:mt-0'>
<div className='text-sm leading-6 text-gray-700'>
<input
className='w-[200px] rounded-lg p-1'
className={`w-[200px] rounded-lg p-1 ${
editMode ? '' : 'bg-gray-200'
}`}
type='text'
id='name'
value={user.name} /* Name */
value={editedName} /* Name */
onChange={e =>
setEditedName(e.target.value)
} /* Update edited name */
disabled={!editMode}
/>
</div>
<div className='mx-[110px] text-sm leading-6 text-gray-700'>
<button
type='submit'
className='flex cursor-pointer flex-row rounded-xl bg-zinc-200 px-3 py-1 transition duration-300 ease-in-out hover:bg-teal-600 hover:text-zinc-100'
>
<PencilIcon className='mr-2 mt-[4px] h-4' />
<p className='font-bold'>Edit</p>
</button>
</div>
</form>
</div>
<div className='px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0'>
Expand All @@ -46,21 +81,18 @@ export default function Settings({ user }) {
<form className='flex flex-row justify-between sm:col-span-1 sm:mt-0'>
<div className='text-sm leading-6 text-gray-700'>
<input
className='w-[200px] rounded-lg p-1'
className={`w-[200px] rounded-lg p-1 ${
editMode ? '' : 'bg-gray-200'
}`}
type='text'
id='name'
value={user.email} /* Email */
value={editedEmail} /* Email */
onChange={e =>
setEditedEmail(e.target.value)
} /* Update edited email */
disabled={!editMode}
/>
</div>
<div className='mx-[110px] text-sm leading-6 text-gray-700'>
<button
type='submit'
className='flex cursor-pointer flex-row rounded-xl bg-zinc-200 px-3 py-1 transition duration-300 ease-in-out hover:bg-teal-600 hover:text-zinc-100'
>
<PencilIcon className='mr-2 mt-[4px] h-4' />
<p className='font-bold'>Edit</p>
</button>
</div>
</form>
</div>
<div className='px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0'>
Expand All @@ -70,21 +102,18 @@ export default function Settings({ user }) {
<form className='flex flex-row justify-between sm:col-span-1 sm:mt-0'>
<div className='text-sm leading-6 text-gray-700'>
<input
className='w-[200px] rounded-lg p-1'
className={`w-[200px] rounded-lg p-1 ${
editMode ? '' : 'bg-gray-200'
}`}
type='text'
id='name'
value={user.name} /* Password */
value={editedPassword} /* Password */
onChange={e =>
setEditedPassword(e.target.value)
} /* Update edited password */
disabled={!editMode}
/>
</div>
<div className='mx-[110px] text-sm leading-6 text-gray-700'>
<button
type='submit'
className='flex cursor-pointer flex-row rounded-xl bg-zinc-200 px-3 py-1 transition duration-300 ease-in-out hover:bg-teal-600 hover:text-zinc-100'
>
<PencilIcon className='mr-2 mt-[4px] h-4' />
<p className='font-bold'>Edit</p>
</button>
</div>
</form>
</div>
<div className='px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0'>
Expand All @@ -94,26 +123,39 @@ export default function Settings({ user }) {
<form className='flex flex-row justify-between sm:col-span-1 sm:mt-0'>
<div className='text-sm leading-6 text-gray-700'>
<input
className='w-[200px] rounded-lg p-1'
className={`w-[200px] rounded-lg p-1 ${
editMode ? '' : 'bg-gray-200'
}`}
type='text'
id='name'
value='Luleå Tekniska Universitet'
value={editedCompany} /* Placeholder */
onChange={e =>
setEditedCompany(e.target.value)
} /* Update edited placeholder */
disabled={!editMode}
/>
</div>
<div className='mx-[110px] text-sm leading-6 text-gray-700'>
<button
type='submit'
className='flex cursor-pointer flex-row rounded-xl bg-zinc-200 px-3 py-1 transition duration-300 ease-in-out hover:bg-teal-600 hover:text-zinc-100'
>
<PencilIcon className='mr-2 mt-[4px] h-4' />
<p className='font-bold'>Edit</p>
</button>
</div>
</form>
</div>
</dl>
</div>
</div>
<div className='mx-[20%] text-sm leading-6 text-gray-700'>
<button
type='button' // Change type to button
onClick={() => {
if (editMode) {
handleSubmit(setEditMode)
} else {
setEditMode(!editMode)
}
}} // Toggle edit mode or submit form
className='flex cursor-pointer flex-row rounded-xl bg-zinc-200 px-3 py-1 transition duration-300 ease-in-out hover:bg-teal-600 hover:text-zinc-100'
>
<PencilIcon className='mr-2 mt-[4px] h-4' />
<p className='font-bold'>{editMode ? 'Submit' : 'Edit'}</p>
</button>
</div>
</div>
)
}
10 changes: 5 additions & 5 deletions src/pages/api/v1/scans.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import Product from '@/models/Product'
import Scan from '@/models/Scans'

const postScans = async (req, res, session) => {
console.log('Här är vår session: ', session)
console.log('Här är vår request: ', req.query)
/* console.log('Här är vår session: ', session)
console.log('Här är vår request: ', req.query) */

if (!session) {
return unauthorized(res)
Expand All @@ -15,7 +15,7 @@ const postScans = async (req, res, session) => {
const fetchedUser = await User.findOne({ email: session.user.email })
const fetchedUserId = fetchedUser._id.toString()

console.log(productId)
/* console.log(productId) */

try {
if (!productId) {
Expand Down Expand Up @@ -43,8 +43,8 @@ const postScans = async (req, res, session) => {
}

const getScans = async (req, res, session) => {
console.log('Här är vår session: ', session)
console.log('Här är vår request: ', req.query)
/* console.log('Här är vår session: ', session)
console.log('Här är vår request: ', req.query) */

if (!session) {
return unauthorized(res)
Expand Down
44 changes: 41 additions & 3 deletions src/pages/api/v1/users/me/[userid].js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { defaultHandler, unauthorized } from '@/utils/server/api-helpers'
import User from '@/models/User'

const getCurrentUser = async (req, res, session) => {
console.log('Här är vår session: ', session)
console.log('Här är vår request: ', req.query)
/* console.log('Här är vår session: ', session)
console.log('Här är vår request: ', req.query) */

if (!session) {
return unauthorized(res)
Expand All @@ -19,7 +19,7 @@ const getCurrentUser = async (req, res, session) => {

const user = await User.findById(req.query.userid)

console.log('vår user ', user)
/* console.log('vår user ', user) */

if (!user) {
return res.status(404).json({ message: 'User not found' })
Expand All @@ -37,12 +37,50 @@ const getCurrentUser = async (req, res, session) => {
}
}

// Function to handle updating user information
const updateUser = async (req, res, session) => {
if (!session) {
return unauthorized(res)
}

try {
// Retrieve user ID from session
const userId = session.user.userId

// Find the user in the database by ID
const user = await User.findById(userId)

if (!user) {
return res.status(404).json({ message: 'User not found' })
}

// Update user information based on request body
user.name = req.body.name
user.email = req.body.email
/* user.password = req.body.password */

// Save the updated user object
await user.save()

// Respond with updated user information
res.json({
name: user.name,
email: user.email,
role: user.role,
})
} catch (error) {
console.error('Error updating user:', error)
res.status(500).json({ message: 'Server Error' })
}
}

const handler = async (req, res) =>
defaultHandler(
req,
res,
{
GET: getCurrentUser,
PUT: updateUser,
},
{
requiresAuth: true,
Expand Down
4 changes: 1 addition & 3 deletions src/pages/profile/[userid].js
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@ export default function Profile() {
return <div>No user data available</div>
}

console.log(user.name)

return (
<LayoutGlobal>
<Container>
Expand Down Expand Up @@ -118,7 +116,7 @@ export default function Profile() {
<div className='border-r-1 h-full border border-zinc-200'></div>
<div className='mx-20 h-[30vw] w-full'>
{activePage === 1 && <Account user={user} />}
{activePage === 2 && <Settings user={user} />}
{activePage === 2 && <Settings user={user} userid={userid} />}
{activePage === 3 && <Scans scans={scans.scans} />}
{activePage === 4 && <Event user={user} />}
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/styles/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

/* styles/globals.css */
body {
background-color: #f4f4f5; /* zinc-100 */
background-color: #fafafa; /* zinc-100 */
}

.active {
Expand Down

0 comments on commit b9e506c

Please sign in to comment.