mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
Additional work on user profile edit
This commit is contained in:
93
src/components/Account/UpdateProfileForm.tsx
Normal file
93
src/components/Account/UpdateProfileForm.tsx
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
import FormError from '@/components/ui/forms/FormError';
|
||||||
|
import FormInfo from '@/components/ui/forms/FormInfo';
|
||||||
|
import FormLabel from '@/components/ui/forms/FormLabel';
|
||||||
|
import FormSegment from '@/components/ui/forms/FormSegment';
|
||||||
|
import Link from 'next/link';
|
||||||
|
import FormTextArea from '@/components/ui/forms/FormTextArea';
|
||||||
|
import { FC } from 'react';
|
||||||
|
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
||||||
|
import type {
|
||||||
|
UseFormHandleSubmit,
|
||||||
|
SubmitHandler,
|
||||||
|
FieldErrors,
|
||||||
|
UseFormRegister,
|
||||||
|
} from 'react-hook-form';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import UpdateProfileSchema from '../../services/User/schema/UpdateProfileSchema';
|
||||||
|
|
||||||
|
type UpdateProfileSchemaT = z.infer<typeof UpdateProfileSchema>;
|
||||||
|
|
||||||
|
interface UpdateProfileFormProps {
|
||||||
|
handleSubmit: UseFormHandleSubmit<UpdateProfileSchemaT>;
|
||||||
|
onSubmit: SubmitHandler<UpdateProfileSchemaT>;
|
||||||
|
errors: FieldErrors<UpdateProfileSchemaT>;
|
||||||
|
isSubmitting: boolean;
|
||||||
|
register: UseFormRegister<UpdateProfileSchemaT>;
|
||||||
|
user: z.infer<typeof GetUserSchema>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const UpdateProfileForm: FC<UpdateProfileFormProps> = ({
|
||||||
|
handleSubmit,
|
||||||
|
onSubmit,
|
||||||
|
errors,
|
||||||
|
isSubmitting,
|
||||||
|
register,
|
||||||
|
user,
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<form className="form-control space-y-1" noValidate onSubmit={handleSubmit(onSubmit)}>
|
||||||
|
<div>
|
||||||
|
<FormInfo>
|
||||||
|
<FormLabel htmlFor="userAvatar">Avatar</FormLabel>
|
||||||
|
<FormError>{errors.userAvatar?.message}</FormError>
|
||||||
|
</FormInfo>
|
||||||
|
<FormSegment>
|
||||||
|
<input
|
||||||
|
disabled={isSubmitting}
|
||||||
|
type="file"
|
||||||
|
id="userAvatar"
|
||||||
|
className="file-input file-input-bordered w-full"
|
||||||
|
{...register('userAvatar')}
|
||||||
|
multiple={false}
|
||||||
|
/>
|
||||||
|
</FormSegment>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<FormInfo>
|
||||||
|
<FormLabel htmlFor="bio">Bio</FormLabel>
|
||||||
|
<FormError>{errors.bio?.message}</FormError>
|
||||||
|
</FormInfo>
|
||||||
|
|
||||||
|
<FormSegment>
|
||||||
|
<FormTextArea
|
||||||
|
disabled={isSubmitting}
|
||||||
|
id="bio"
|
||||||
|
{...register('bio')}
|
||||||
|
rows={5}
|
||||||
|
formValidationSchema={register('bio')}
|
||||||
|
error={!!errors.bio}
|
||||||
|
placeholder="Bio"
|
||||||
|
/>
|
||||||
|
</FormSegment>
|
||||||
|
</div>
|
||||||
|
<div className="mt-6 flex w-full flex-col justify-center space-y-3">
|
||||||
|
<Link
|
||||||
|
className={`btn btn-secondary rounded-xl ${isSubmitting ? 'btn-disabled' : ''}`}
|
||||||
|
href={`/users/${user?.id}`}
|
||||||
|
>
|
||||||
|
Cancel Changes
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<button
|
||||||
|
className="btn btn-primary w-full rounded-xl"
|
||||||
|
type="submit"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
>
|
||||||
|
Save Changes
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default UpdateProfileForm;
|
||||||
@@ -31,50 +31,50 @@ const UserHeader: FC<UserHeaderProps> = ({ user }) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="card items-center text-center">
|
<header className="card items-center text-center">
|
||||||
<div className="card-body w-full items-center">
|
<div className="card-body w-full items-center justify-center">
|
||||||
<div className="h-40 w-40">
|
<div className="h-40 w-40">
|
||||||
<UserAvatar user={user} />
|
<UserAvatar user={user} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold lg:text-4xl">{user.username}</h1>
|
<h1 className="text-2xl font-bold lg:text-4xl">{user.username}</h1>
|
||||||
|
|
||||||
|
<div className="flex space-x-3 text-lg font-bold">
|
||||||
|
<span>{followingCount} Following</span>
|
||||||
|
<span>{followerCount} Followers</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="italic">
|
||||||
|
joined{' '}
|
||||||
|
{timeDistance && (
|
||||||
|
<span
|
||||||
|
className="tooltip tooltip-bottom"
|
||||||
|
data-tip={format(new Date(user.createdAt), 'MM/dd/yyyy')}
|
||||||
|
>
|
||||||
|
{`${timeDistance} ago`}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex space-x-3 text-lg font-bold">
|
<div className="my-2 w-6/12">
|
||||||
<span>{followingCount} Following</span>
|
|
||||||
<span>{followerCount} Followers</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<span className="italic">
|
|
||||||
joined{' '}
|
|
||||||
{timeDistance && (
|
|
||||||
<span
|
|
||||||
className="tooltip tooltip-bottom"
|
|
||||||
data-tip={format(new Date(user.createdAt), 'MM/dd/yyyy')}
|
|
||||||
>
|
|
||||||
{`${timeDistance} ago`}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
<div className="w-6/12">
|
|
||||||
<p className="text-sm">{user.bio}</p>
|
<p className="text-sm">{user.bio}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{currentUser?.id !== user.id ? (
|
<div className="my-2 flex items-center justify-center">
|
||||||
<div className="flex items-center justify-center">
|
{currentUser?.id !== user.id ? (
|
||||||
<UserFollowButton
|
<UserFollowButton
|
||||||
mutateFollowerCount={mutateFollowerCount}
|
mutateFollowerCount={mutateFollowerCount}
|
||||||
user={user}
|
user={user}
|
||||||
mutateFollowingCount={mutateFollowingCount}
|
mutateFollowingCount={mutateFollowingCount}
|
||||||
/>
|
/>
|
||||||
</div>
|
) : (
|
||||||
) : (
|
|
||||||
<div className="flex items-center justify-center">
|
|
||||||
<Link href={`/account/profile`} className="btn btn-primary">
|
<Link href={`/account/profile`} className="btn btn-primary">
|
||||||
Edit Profile
|
Edit Profile
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
)}
|
||||||
)}
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,16 +1,38 @@
|
|||||||
|
/**
|
||||||
|
* Custom hook using SWR for fetching users followed by a specific user.
|
||||||
|
*
|
||||||
|
* @param options - The options for fetching users.
|
||||||
|
* @param [options.pageSize=5] - The number of users to fetch per page. Default is `5`
|
||||||
|
* @param options.userId - The ID of the user.
|
||||||
|
* @returns An object with the following properties:
|
||||||
|
*
|
||||||
|
* - `following` The list of users followed by the specified user.
|
||||||
|
* - `followingCount` The total count of users followed by the specified user.
|
||||||
|
* - `pageCount` The total number of pages.
|
||||||
|
* - `size` The current page size.
|
||||||
|
* - `setSize` A function to set the page size.
|
||||||
|
* - `isLoading` Indicates if the data is currently being loaded.
|
||||||
|
* - `isLoadingMore` Indicates if there are more pages to load.
|
||||||
|
* - `isAtEnd` Indicates if the current page is the last page.
|
||||||
|
* - `mutate` A function to mutate the data.
|
||||||
|
* - `error` The error object, if any.
|
||||||
|
*/
|
||||||
import FollowInfoSchema from '@/services/UserFollows/schema/FollowInfoSchema';
|
import FollowInfoSchema from '@/services/UserFollows/schema/FollowInfoSchema';
|
||||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||||
import useSWRInfinite from 'swr/infinite';
|
import useSWRInfinite from 'swr/infinite';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
const useGetUsersFollowedByUser = ({
|
const useGetUsersFollowedByUser = ({
|
||||||
pageSize,
|
pageSize = 5,
|
||||||
userId,
|
userId,
|
||||||
}: {
|
}: {
|
||||||
pageSize: number;
|
pageSize?: number;
|
||||||
userId: string;
|
userId: string | undefined;
|
||||||
}) => {
|
}) => {
|
||||||
const fetcher = async (url: string) => {
|
const fetcher = async (url: string | undefined) => {
|
||||||
|
if (!url) {
|
||||||
|
throw new Error('URL is undefined');
|
||||||
|
}
|
||||||
const response = await fetch(url);
|
const response = await fetch(url);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(response.statusText);
|
throw new Error(response.statusText);
|
||||||
|
|||||||
@@ -3,13 +3,35 @@ import APIResponseValidationSchema from '@/validation/APIResponseValidationSchem
|
|||||||
import useSWRInfinite from 'swr/infinite';
|
import useSWRInfinite from 'swr/infinite';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
const useGetUsersFollowingUser = ({
|
interface UseGetUsersFollowingUser {
|
||||||
pageSize,
|
pageSize?: number;
|
||||||
userId,
|
userId?: string;
|
||||||
}: {
|
}
|
||||||
pageSize: number;
|
|
||||||
userId: string;
|
/**
|
||||||
}) => {
|
* Custom hook using SWR for fetching users followed by a specific user.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const { followers, followerCount } = useGetUsersFollowingUser({ userId: '123' });
|
||||||
|
*
|
||||||
|
* @param options - The options for fetching users.
|
||||||
|
* @param [options.pageSize=5] - The number of users to fetch per page. Default is `5`
|
||||||
|
* @param options.userId - The ID of the user.
|
||||||
|
* @returns An object with the following properties:
|
||||||
|
*
|
||||||
|
* - `followers` The list of users following the specified user.
|
||||||
|
* - `followerCount` The total count of users following the specified user.
|
||||||
|
* - `pageCount` The total number of pages.
|
||||||
|
* - `size` The current page size.
|
||||||
|
* - `setSize` A function to set the page size.
|
||||||
|
* - `isLoading` Indicates if the data is currently being loaded.
|
||||||
|
* - `isLoadingMore` Indicates if there are more pages to load.
|
||||||
|
* - `isAtEnd` Indicates if the current page is the last page.
|
||||||
|
* - `mutate` A function to mutate the data.
|
||||||
|
* - `error` The error object, if any.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const useGetUsersFollowingUser = ({ pageSize = 5, userId }: UseGetUsersFollowingUser) => {
|
||||||
const fetcher = async (url: string) => {
|
const fetcher = async (url: string) => {
|
||||||
const response = await fetch(url);
|
const response = await fetch(url);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ const useNavbar = () => {
|
|||||||
|
|
||||||
const authenticatedPages: readonly Page[] = [
|
const authenticatedPages: readonly Page[] = [
|
||||||
{ slug: '/account', name: 'Account' },
|
{ slug: '/account', name: 'Account' },
|
||||||
|
{ slug: `/users/${user?.id}`, name: 'Profile' },
|
||||||
{ slug: '/api/users/logout', name: 'Logout' },
|
{ slug: '/api/users/logout', name: 'Logout' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,3 @@
|
|||||||
import FormError from '@/components/ui/forms/FormError';
|
|
||||||
import FormInfo from '@/components/ui/forms/FormInfo';
|
|
||||||
import FormLabel from '@/components/ui/forms/FormLabel';
|
|
||||||
import FormSegment from '@/components/ui/forms/FormSegment';
|
|
||||||
import FormTextInput from '@/components/ui/forms/FormTextInput';
|
|
||||||
import findUserById from '@/services/User/findUserById';
|
|
||||||
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
|
||||||
import withPageAuthRequired from '@/util/withPageAuthRequired';
|
import withPageAuthRequired from '@/util/withPageAuthRequired';
|
||||||
import { GetServerSideProps, NextPage } from 'next';
|
import { GetServerSideProps, NextPage } from 'next';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
@@ -13,74 +6,42 @@ import { zodResolver } from '@hookform/resolvers/zod';
|
|||||||
import { SubmitHandler, useForm } from 'react-hook-form';
|
import { SubmitHandler, useForm } from 'react-hook-form';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
import createErrorToast from '@/util/createErrorToast';
|
import createErrorToast from '@/util/createErrorToast';
|
||||||
import Button from '@/components/ui/forms/Button';
|
|
||||||
|
|
||||||
interface ProfilePageProps {
|
import UserAvatar from '@/components/Account/UserAvatar';
|
||||||
user: z.infer<typeof GetUserSchema>;
|
import { useContext, useEffect } from 'react';
|
||||||
}
|
import UserContext from '@/contexts/UserContext';
|
||||||
|
|
||||||
const UpdateProfileSchema = z.object({
|
import useGetUsersFollowedByUser from '@/hooks/data-fetching/user-follows/useGetUsersFollowedByUser';
|
||||||
bio: z.string().min(1, 'Bio cannot be empty'),
|
import useGetUsersFollowingUser from '@/hooks/data-fetching/user-follows/useGetUsersFollowingUser';
|
||||||
userAvatar: z
|
import Head from 'next/head';
|
||||||
.instanceof(typeof FileList !== 'undefined' ? FileList : Object)
|
|
||||||
.refine((fileList) => fileList instanceof FileList, {
|
|
||||||
message: 'You must submit this form in a web browser.',
|
|
||||||
})
|
|
||||||
.refine((fileList) => (fileList as FileList).length === 1, {
|
|
||||||
message: 'You must upload exactly one file.',
|
|
||||||
})
|
|
||||||
.refine(
|
|
||||||
(fileList) =>
|
|
||||||
[...(fileList as FileList)]
|
|
||||||
.map((file) => file.type)
|
|
||||||
.every((fileType) => fileType.startsWith('image/')),
|
|
||||||
{ message: 'You must upload only images.' },
|
|
||||||
)
|
|
||||||
.refine(
|
|
||||||
(fileList) =>
|
|
||||||
[...(fileList as FileList)]
|
|
||||||
.map((file) => file.size)
|
|
||||||
.every((fileSize) => fileSize < 15 * 1024 * 1024),
|
|
||||||
{ message: 'You must upload images smaller than 15MB.' },
|
|
||||||
),
|
|
||||||
});
|
|
||||||
|
|
||||||
const sendUpdateProfileRequest = async (data: z.infer<typeof UpdateProfileSchema>) => {
|
import UpdateProfileSchema from '../../services/User/schema/UpdateProfileSchema';
|
||||||
if (!(data.userAvatar instanceof FileList)) {
|
import sendUpdateProfileRequest from '../../requests/Account/sendUpdateProfileRequest';
|
||||||
throw new Error('You must submit this form in a web browser.');
|
import UpdateProfileForm from '../../components/Account/UpdateProfileForm';
|
||||||
}
|
|
||||||
|
|
||||||
const { bio, userAvatar } = data;
|
const ProfilePage: NextPage = () => {
|
||||||
|
const { user, mutate: mutateUser } = useContext(UserContext);
|
||||||
|
|
||||||
const formData = new FormData();
|
|
||||||
formData.append('image', userAvatar[0]);
|
|
||||||
formData.append('bio', bio);
|
|
||||||
|
|
||||||
const response = await fetch(`/api/users/profile`, {
|
|
||||||
method: 'PUT',
|
|
||||||
body: formData,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error('Something went wrong.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedUser = await response.json();
|
|
||||||
|
|
||||||
return updatedUser;
|
|
||||||
};
|
|
||||||
|
|
||||||
const ProfilePage: NextPage<ProfilePageProps> = ({ user }) => {
|
|
||||||
const {
|
const {
|
||||||
register,
|
register,
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
|
setValue,
|
||||||
formState: { errors, isSubmitting },
|
formState: { errors, isSubmitting },
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
watch,
|
||||||
|
|
||||||
reset,
|
reset,
|
||||||
} = useForm<z.infer<typeof UpdateProfileSchema>>({
|
} = useForm<z.infer<typeof UpdateProfileSchema>>({
|
||||||
resolver: zodResolver(UpdateProfileSchema),
|
resolver: zodResolver(UpdateProfileSchema),
|
||||||
|
defaultValues: {
|
||||||
|
bio: user?.bio ?? '',
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!user || !user.bio) return;
|
||||||
|
setValue('bio', user.bio);
|
||||||
|
}, [user, setValue]);
|
||||||
|
|
||||||
const onSubmit: SubmitHandler<z.infer<typeof UpdateProfileSchema>> = async (data) => {
|
const onSubmit: SubmitHandler<z.infer<typeof UpdateProfileSchema>> = async (data) => {
|
||||||
try {
|
try {
|
||||||
await sendUpdateProfileRequest(data);
|
await sendUpdateProfileRequest(data);
|
||||||
@@ -89,69 +50,103 @@ const ProfilePage: NextPage<ProfilePageProps> = ({ user }) => {
|
|||||||
setTimeout(resolve, 1000);
|
setTimeout(resolve, 1000);
|
||||||
});
|
});
|
||||||
toast.remove(loadingToast);
|
toast.remove(loadingToast);
|
||||||
// reset();
|
reset();
|
||||||
|
mutateUser!();
|
||||||
toast.success('Profile updated!');
|
toast.success('Profile updated!');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
createErrorToast(error);
|
createErrorToast(error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
const { followingCount } = useGetUsersFollowedByUser({
|
||||||
|
userId: user?.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { followerCount } = useGetUsersFollowingUser({
|
||||||
|
userId: user?.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const getUserAvatarPath = () => {
|
||||||
|
const watchedInput = watch('userAvatar');
|
||||||
|
|
||||||
|
if (
|
||||||
|
!(watchedInput instanceof FileList) ||
|
||||||
|
watchedInput.length !== 1 ||
|
||||||
|
!watchedInput[0].type.startsWith('image/')
|
||||||
|
) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
const [avatar] = watchedInput;
|
||||||
|
|
||||||
|
return URL.createObjectURL(avatar);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col items-center justify-center">
|
<>
|
||||||
<div className="w-9/12">
|
<Head>
|
||||||
<pre>{JSON.stringify(user, null, 2)}</pre>
|
<title>The Biergarten App || Update Your Profile</title>
|
||||||
<form className="form-control" noValidate onSubmit={handleSubmit(onSubmit)}>
|
<meta name="description" content="Update your user profile." />
|
||||||
<FormInfo>
|
</Head>
|
||||||
<FormLabel htmlFor="bio">Bio</FormLabel>
|
<div className="mt-20 flex flex-col items-center justify-center">
|
||||||
<FormError>{errors.bio?.message}</FormError>
|
{user && (
|
||||||
</FormInfo>
|
<div className="w-10/12 lg:w-7/12">
|
||||||
|
<div className="card">
|
||||||
|
<div className="card-body">
|
||||||
|
<div className="my-10 flex flex-col items-center justify-center">
|
||||||
|
<div className="my-5 h-52">
|
||||||
|
<UserAvatar
|
||||||
|
user={{
|
||||||
|
...user,
|
||||||
|
userAvatar:
|
||||||
|
// Render the user's avatar if they have one and then switch to the preview it's being updated.
|
||||||
|
user.userAvatar && !getUserAvatarPath()
|
||||||
|
? user.userAvatar
|
||||||
|
: {
|
||||||
|
id: 'preview',
|
||||||
|
alt: 'User Avatar',
|
||||||
|
caption: 'User Avatar',
|
||||||
|
path: getUserAvatarPath(),
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="text-center">
|
||||||
|
<h2 className="text-3xl font-bold">{user.username}</h2>
|
||||||
|
|
||||||
<FormSegment>
|
<div className="flex space-x-3 text-lg font-bold">
|
||||||
<FormTextInput
|
<span>{followingCount} Following</span>
|
||||||
disabled={isSubmitting}
|
<span>{followerCount} Followers</span>
|
||||||
id="bio"
|
</div>
|
||||||
type="text"
|
</div>
|
||||||
formValidationSchema={register('bio')}
|
|
||||||
error={!!errors.bio}
|
|
||||||
placeholder="Bio"
|
|
||||||
/>
|
|
||||||
</FormSegment>
|
|
||||||
|
|
||||||
<FormInfo>
|
<div>
|
||||||
<FormLabel htmlFor="userAvatar">Avatar</FormLabel>
|
<p className="text-lg">
|
||||||
<FormError>{errors.userAvatar?.message}</FormError>
|
{watch('bio') || (
|
||||||
</FormInfo>
|
<span className="italic">Your bio will appear here.</span>
|
||||||
<FormSegment>
|
)}
|
||||||
<input
|
</p>
|
||||||
disabled={isSubmitting}
|
</div>
|
||||||
type="file"
|
</div>
|
||||||
id="userAvatar"
|
|
||||||
className="file-input file-input-bordered w-full"
|
|
||||||
{...register('userAvatar')}
|
|
||||||
/>
|
|
||||||
</FormSegment>
|
|
||||||
|
|
||||||
<div className="mt-6">
|
<UpdateProfileForm
|
||||||
<Button type="submit" isSubmitting={isSubmitting}>
|
handleSubmit={handleSubmit}
|
||||||
Update Profile
|
onSubmit={onSubmit}
|
||||||
</Button>
|
errors={errors}
|
||||||
|
isSubmitting={isSubmitting}
|
||||||
|
register={register}
|
||||||
|
user={user}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default ProfilePage;
|
export default ProfilePage;
|
||||||
|
|
||||||
export const getServerSideProps: GetServerSideProps =
|
export const getServerSideProps: GetServerSideProps = withPageAuthRequired();
|
||||||
withPageAuthRequired<ProfilePageProps>(async (context, session) => {
|
|
||||||
const { id } = session;
|
|
||||||
|
|
||||||
const user = await findUserById(id);
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return { notFound: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
return { props: { user: JSON.parse(JSON.stringify(user)) } };
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { createRouter } from 'next-connect';
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
interface UpdateProfileRequest extends UserExtendedNextApiRequest {
|
interface UpdateProfileRequest extends UserExtendedNextApiRequest {
|
||||||
file?: Express.Multer.File;
|
file: Express.Multer.File;
|
||||||
body: {
|
body: {
|
||||||
bio: string;
|
bio: string;
|
||||||
};
|
};
|
||||||
@@ -30,14 +30,26 @@ interface UpdateUserProfileByIdParams {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const updateUserProfileById = async ({ id, data }: UpdateUserProfileByIdParams) => {
|
const updateUserProfileById = async ({ id, data }: UpdateUserProfileByIdParams) => {
|
||||||
const { alt, path, caption } = data.avatar;
|
|
||||||
const user: z.infer<typeof GetUserSchema> = await DBClient.instance.user.update({
|
const user: z.infer<typeof GetUserSchema> = await DBClient.instance.user.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data: {
|
data: {
|
||||||
bio: data.bio,
|
bio: data.bio,
|
||||||
userAvatar: {
|
userAvatar: data.avatar
|
||||||
upsert: { create: { alt, path, caption }, update: { alt, path, caption } },
|
? {
|
||||||
},
|
upsert: {
|
||||||
|
create: {
|
||||||
|
alt: data.avatar.alt,
|
||||||
|
path: data.avatar.path,
|
||||||
|
caption: data.avatar.caption,
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
alt: data.avatar.alt,
|
||||||
|
path: data.avatar.path,
|
||||||
|
caption: data.avatar.caption,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
},
|
},
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
@@ -61,10 +73,6 @@ const updateUserProfileById = async ({ id, data }: UpdateUserProfileByIdParams)
|
|||||||
const updateProfile = async (req: UpdateProfileRequest, res: NextApiResponse) => {
|
const updateProfile = async (req: UpdateProfileRequest, res: NextApiResponse) => {
|
||||||
const { file, body, user } = req;
|
const { file, body, user } = req;
|
||||||
|
|
||||||
if (!file) {
|
|
||||||
throw new Error('No file uploaded');
|
|
||||||
}
|
|
||||||
|
|
||||||
await updateUserProfileById({
|
await updateUserProfileById({
|
||||||
id: user!.id,
|
id: user!.id,
|
||||||
data: {
|
data: {
|
||||||
@@ -86,10 +94,11 @@ const router = createRouter<
|
|||||||
|
|
||||||
router.put(
|
router.put(
|
||||||
getCurrentUser,
|
getCurrentUser,
|
||||||
|
|
||||||
// @ts-expect-error
|
// @ts-expect-error
|
||||||
singleUploadMiddleware,
|
singleUploadMiddleware,
|
||||||
|
|
||||||
validateRequest({ bodySchema: z.object({ bio: z.string().max(1000) }) }),
|
validateRequest({ bodySchema: z.object({ bio: z.string().max(1000) }) }),
|
||||||
|
|
||||||
updateProfile,
|
updateProfile,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
32
src/requests/Account/sendUpdateProfileRequest.tsx
Normal file
32
src/requests/Account/sendUpdateProfileRequest.tsx
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import UpdateProfileSchema from '@/services/User/schema/UpdateProfileSchema';
|
||||||
|
|
||||||
|
const sendUpdateProfileRequest = async (data: z.infer<typeof UpdateProfileSchema>) => {
|
||||||
|
if (!(data.userAvatar instanceof FileList)) {
|
||||||
|
throw new Error('You must submit this form in a web browser.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { bio, userAvatar } = data;
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
if (userAvatar[0]) {
|
||||||
|
formData.append('image', userAvatar[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
formData.append('bio', bio);
|
||||||
|
|
||||||
|
const response = await fetch(`/api/users/profile`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Something went wrong.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedUser = await response.json();
|
||||||
|
|
||||||
|
return updatedUser;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default sendUpdateProfileRequest;
|
||||||
28
src/services/User/schema/UpdateProfileSchema.tsx
Normal file
28
src/services/User/schema/UpdateProfileSchema.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
const UpdateProfileSchema = z.object({
|
||||||
|
bio: z.string().min(1, 'Bio cannot be empty'),
|
||||||
|
userAvatar: z.optional(
|
||||||
|
z
|
||||||
|
.instanceof(typeof FileList !== 'undefined' ? FileList : Object)
|
||||||
|
.refine((fileList) => fileList instanceof FileList, {
|
||||||
|
message: 'You must submit this form in a web browser.',
|
||||||
|
})
|
||||||
|
.refine(
|
||||||
|
(fileList) =>
|
||||||
|
[...(fileList as FileList)]
|
||||||
|
.map((file) => file.type)
|
||||||
|
.every((fileType) => fileType.startsWith('image/')),
|
||||||
|
{ message: 'You must upload only images.' },
|
||||||
|
)
|
||||||
|
.refine(
|
||||||
|
(fileList) =>
|
||||||
|
[...(fileList as FileList)]
|
||||||
|
.map((file) => file.size)
|
||||||
|
.every((fileSize) => fileSize < 15 * 1024 * 1024),
|
||||||
|
{ message: 'You must upload images smaller than 15MB.' },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
export default UpdateProfileSchema;
|
||||||
@@ -17,8 +17,8 @@ const myThemes = {
|
|||||||
'base-300': 'hsl(227, 20%, 10%)',
|
'base-300': 'hsl(227, 20%, 10%)',
|
||||||
},
|
},
|
||||||
light: {
|
light: {
|
||||||
primary: 'hsl(180, 15%, 70%)',
|
primary: 'hsl(180, 20%, 70%)',
|
||||||
secondary: 'hsl(21, 54%, 83%)',
|
secondary: 'hsl(120, 10%, 70%)',
|
||||||
error: 'hsl(4, 87%, 74%)',
|
error: 'hsl(4, 87%, 74%)',
|
||||||
accent: 'hsl(93, 27%, 73%)',
|
accent: 'hsl(93, 27%, 73%)',
|
||||||
neutral: 'hsl(38, 31%, 91%)',
|
neutral: 'hsl(38, 31%, 91%)',
|
||||||
|
|||||||
Reference in New Issue
Block a user