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 (
|
||||
<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">
|
||||
<UserAvatar user={user} />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<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 className="flex space-x-3 text-lg font-bold">
|
||||
<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">
|
||||
<div className="my-2 w-6/12">
|
||||
<p className="text-sm">{user.bio}</p>
|
||||
</div>
|
||||
|
||||
{currentUser?.id !== user.id ? (
|
||||
<div className="flex items-center justify-center">
|
||||
<div className="my-2 flex items-center justify-center">
|
||||
{currentUser?.id !== user.id ? (
|
||||
<UserFollowButton
|
||||
mutateFollowerCount={mutateFollowerCount}
|
||||
user={user}
|
||||
mutateFollowingCount={mutateFollowingCount}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-center">
|
||||
) : (
|
||||
<Link href={`/account/profile`} className="btn btn-primary">
|
||||
Edit Profile
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</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 APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import useSWRInfinite from 'swr/infinite';
|
||||
import { z } from 'zod';
|
||||
|
||||
const useGetUsersFollowedByUser = ({
|
||||
pageSize,
|
||||
pageSize = 5,
|
||||
userId,
|
||||
}: {
|
||||
pageSize: number;
|
||||
userId: string;
|
||||
pageSize?: number;
|
||||
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);
|
||||
if (!response.ok) {
|
||||
throw new Error(response.statusText);
|
||||
|
||||
@@ -3,13 +3,35 @@ import APIResponseValidationSchema from '@/validation/APIResponseValidationSchem
|
||||
import useSWRInfinite from 'swr/infinite';
|
||||
import { z } from 'zod';
|
||||
|
||||
const useGetUsersFollowingUser = ({
|
||||
pageSize,
|
||||
userId,
|
||||
}: {
|
||||
pageSize: number;
|
||||
userId: string;
|
||||
}) => {
|
||||
interface UseGetUsersFollowingUser {
|
||||
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 response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
|
||||
@@ -24,6 +24,7 @@ const useNavbar = () => {
|
||||
|
||||
const authenticatedPages: readonly Page[] = [
|
||||
{ slug: '/account', name: 'Account' },
|
||||
{ slug: `/users/${user?.id}`, name: 'Profile' },
|
||||
{ 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 { GetServerSideProps, NextPage } from 'next';
|
||||
import { z } from 'zod';
|
||||
@@ -13,74 +6,42 @@ import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { SubmitHandler, useForm } from 'react-hook-form';
|
||||
import toast from 'react-hot-toast';
|
||||
import createErrorToast from '@/util/createErrorToast';
|
||||
import Button from '@/components/ui/forms/Button';
|
||||
|
||||
interface ProfilePageProps {
|
||||
user: z.infer<typeof GetUserSchema>;
|
||||
}
|
||||
import UserAvatar from '@/components/Account/UserAvatar';
|
||||
import { useContext, useEffect } from 'react';
|
||||
import UserContext from '@/contexts/UserContext';
|
||||
|
||||
const UpdateProfileSchema = z.object({
|
||||
bio: z.string().min(1, 'Bio cannot be empty'),
|
||||
userAvatar: 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).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.' },
|
||||
),
|
||||
});
|
||||
import useGetUsersFollowedByUser from '@/hooks/data-fetching/user-follows/useGetUsersFollowedByUser';
|
||||
import useGetUsersFollowingUser from '@/hooks/data-fetching/user-follows/useGetUsersFollowingUser';
|
||||
import Head from 'next/head';
|
||||
|
||||
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.');
|
||||
}
|
||||
import UpdateProfileSchema from '../../services/User/schema/UpdateProfileSchema';
|
||||
import sendUpdateProfileRequest from '../../requests/Account/sendUpdateProfileRequest';
|
||||
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 {
|
||||
register,
|
||||
handleSubmit,
|
||||
setValue,
|
||||
formState: { errors, isSubmitting },
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
watch,
|
||||
|
||||
reset,
|
||||
} = useForm<z.infer<typeof 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) => {
|
||||
try {
|
||||
await sendUpdateProfileRequest(data);
|
||||
@@ -89,69 +50,103 @@ const ProfilePage: NextPage<ProfilePageProps> = ({ user }) => {
|
||||
setTimeout(resolve, 1000);
|
||||
});
|
||||
toast.remove(loadingToast);
|
||||
// reset();
|
||||
reset();
|
||||
mutateUser!();
|
||||
toast.success('Profile updated!');
|
||||
} catch (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 (
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
<div className="w-9/12">
|
||||
<pre>{JSON.stringify(user, null, 2)}</pre>
|
||||
<form className="form-control" noValidate onSubmit={handleSubmit(onSubmit)}>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="bio">Bio</FormLabel>
|
||||
<FormError>{errors.bio?.message}</FormError>
|
||||
</FormInfo>
|
||||
<>
|
||||
<Head>
|
||||
<title>The Biergarten App || Update Your Profile</title>
|
||||
<meta name="description" content="Update your user profile." />
|
||||
</Head>
|
||||
<div className="mt-20 flex flex-col items-center justify-center">
|
||||
{user && (
|
||||
<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>
|
||||
<FormTextInput
|
||||
disabled={isSubmitting}
|
||||
id="bio"
|
||||
type="text"
|
||||
formValidationSchema={register('bio')}
|
||||
error={!!errors.bio}
|
||||
placeholder="Bio"
|
||||
/>
|
||||
</FormSegment>
|
||||
<div className="flex space-x-3 text-lg font-bold">
|
||||
<span>{followingCount} Following</span>
|
||||
<span>{followerCount} Followers</span>
|
||||
</div>
|
||||
</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')}
|
||||
/>
|
||||
</FormSegment>
|
||||
<div>
|
||||
<p className="text-lg">
|
||||
{watch('bio') || (
|
||||
<span className="italic">Your bio will appear here.</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6">
|
||||
<Button type="submit" isSubmitting={isSubmitting}>
|
||||
Update Profile
|
||||
</Button>
|
||||
<UpdateProfileForm
|
||||
handleSubmit={handleSubmit}
|
||||
onSubmit={onSubmit}
|
||||
errors={errors}
|
||||
isSubmitting={isSubmitting}
|
||||
register={register}
|
||||
user={user}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProfilePage;
|
||||
|
||||
export const getServerSideProps: GetServerSideProps =
|
||||
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)) } };
|
||||
});
|
||||
export const getServerSideProps: GetServerSideProps = withPageAuthRequired();
|
||||
|
||||
@@ -11,7 +11,7 @@ import { createRouter } from 'next-connect';
|
||||
import { z } from 'zod';
|
||||
|
||||
interface UpdateProfileRequest extends UserExtendedNextApiRequest {
|
||||
file?: Express.Multer.File;
|
||||
file: Express.Multer.File;
|
||||
body: {
|
||||
bio: string;
|
||||
};
|
||||
@@ -30,14 +30,26 @@ interface UpdateUserProfileByIdParams {
|
||||
}
|
||||
|
||||
const updateUserProfileById = async ({ id, data }: UpdateUserProfileByIdParams) => {
|
||||
const { alt, path, caption } = data.avatar;
|
||||
const user: z.infer<typeof GetUserSchema> = await DBClient.instance.user.update({
|
||||
where: { id },
|
||||
data: {
|
||||
bio: data.bio,
|
||||
userAvatar: {
|
||||
upsert: { create: { alt, path, caption }, update: { alt, path, caption } },
|
||||
},
|
||||
userAvatar: data.avatar
|
||||
? {
|
||||
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: {
|
||||
id: true,
|
||||
@@ -61,10 +73,6 @@ const updateUserProfileById = async ({ id, data }: UpdateUserProfileByIdParams)
|
||||
const updateProfile = async (req: UpdateProfileRequest, res: NextApiResponse) => {
|
||||
const { file, body, user } = req;
|
||||
|
||||
if (!file) {
|
||||
throw new Error('No file uploaded');
|
||||
}
|
||||
|
||||
await updateUserProfileById({
|
||||
id: user!.id,
|
||||
data: {
|
||||
@@ -86,10 +94,11 @@ const router = createRouter<
|
||||
|
||||
router.put(
|
||||
getCurrentUser,
|
||||
|
||||
// @ts-expect-error
|
||||
singleUploadMiddleware,
|
||||
|
||||
validateRequest({ bodySchema: z.object({ bio: z.string().max(1000) }) }),
|
||||
|
||||
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%)',
|
||||
},
|
||||
light: {
|
||||
primary: 'hsl(180, 15%, 70%)',
|
||||
secondary: 'hsl(21, 54%, 83%)',
|
||||
primary: 'hsl(180, 20%, 70%)',
|
||||
secondary: 'hsl(120, 10%, 70%)',
|
||||
error: 'hsl(4, 87%, 74%)',
|
||||
accent: 'hsl(93, 27%, 73%)',
|
||||
neutral: 'hsl(38, 31%, 91%)',
|
||||
|
||||
Reference in New Issue
Block a user