Skip to content

Commit

Permalink
fix styling, add catch errors, add loading
Browse files Browse the repository at this point in the history
  • Loading branch information
135ze committed Nov 13, 2024
1 parent c9b5e7c commit 2c7bce5
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 41 deletions.
16 changes: 12 additions & 4 deletions src/pages/api/users.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { NextApiResponse } from 'next';
import type { NextApiRequest, NextApiResponse } from 'next';
import { prisma } from '../../../utils/prisma';

export default async function handler(req, res: NextApiResponse) {
const users = await prisma.user.findMany();
res.status(200).json(users);
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const users = await prisma.user.findMany();
res.status(200).json(users);
} catch (error) {
console.error('Error fetching users:', error);
res.status(500).json({ error: 'Internal server error' });
}
}
32 changes: 14 additions & 18 deletions src/pages/api/users/[id].ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'GET') {
const params = req.query;
const getAbsences = params.getAbsences === 'true';
const id = Number(params.id as string);
const id = Number(req.query.id);

if (Number.isNaN(id)) {
return res.status(400).json({ error: 'Invalid ID provided' });
}
if (Number.isNaN(id)) {
return res.status(400).json({ error: 'Invalid ID provided' });
}

if (req.method === 'GET') {
const getAbsences = req.query.getAbsences === 'true';

try {
const user = await prisma.user.findUnique({
Expand All @@ -21,15 +21,16 @@ export default async function handler(
});

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

return res.status(200).json(user);
} catch {
} catch (error) {
console.error('Error fetching user:', error);
return res.status(500).json({ error: 'Internal server error' });
}
} else if (req.method === 'PATCH') {
const data = req.body;
const { email, firstName, lastName, role, status } = req.body;
const id = Number(req.query.id as string);

if (Number.isNaN(id)) {
Expand All @@ -39,21 +40,16 @@ export default async function handler(
try {
const updatedUser = await prisma.user.update({
where: { id },
data: {
email: data.email,
firstName: data.firstName,
lastName: data.lastName,
role: data.role,
status: data.status,
},
data: { email, firstName, lastName, role, status },
});

if (!updatedUser) {
return res.status(400).json({ error: 'User not found' });
}

return res.status(200).json(updatedUser);
} catch {
} catch (error) {
console.error('Error updating user:', error);
return res.status(500).json({ error: 'Internal server error' });
}
} else {
Expand Down
42 changes: 23 additions & 19 deletions src/pages/manage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ interface User {

export default function AnotherPage() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState<boolean>(true);

useEffect(() => {
const fetchUsers = async () => {
Expand All @@ -23,8 +24,12 @@ export default function AnotherPage() {
}
const data: User[] = await response.json();
setUsers(data);
} catch (error) {
console.error('Error fetching users:', error);
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error fetching users:', error.message);
}
} finally {
setLoading(false);
}
};

Expand All @@ -33,15 +38,18 @@ export default function AnotherPage() {

const updateUserRole = async (userId: number, newRole: string) => {
const confirmed = window.confirm('Confirm change role to ' + newRole);

if (!confirmed) {
return;
}
if (!confirmed) return;

const apiUrl = `/api/users/${userId}`;
const originalUsers = [...users];

setUsers((prevUsers) =>
prevUsers.map((user) =>
user.id === userId ? { ...user, role: newRole } : user
)
);

try {
// update server side
const response = await fetch(apiUrl, {
method: 'PATCH',
headers: {
Expand All @@ -51,24 +59,22 @@ export default function AnotherPage() {
});

if (!response.ok) {
setUsers(originalUsers);
throw new Error(response.statusText);
}

// update in frontend
setUsers(
users.map((user) =>
user.id === userId ? { ...user, role: newRole } : user
)
);
} catch (error) {
console.error('Error updating user:', error);
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error updating user:', error.message);
}
}
};

return (
<div>
<h1>Admin Management</h1>
{users ? (
{loading ? (
<p>Loading...</p>
) : (
<table>
<thead>
<tr>
Expand Down Expand Up @@ -97,8 +103,6 @@ export default function AnotherPage() {
))}
</tbody>
</table>
) : (
<p>Loading...</p>
)}
</div>
);
Expand Down

0 comments on commit 2c7bce5

Please sign in to comment.