Restructure account api routes, fix update profile

This commit is contained in:
Aaron William Po
2023-12-02 22:42:07 -05:00
parent 0d23b02957
commit cf89dc92df
15 changed files with 366 additions and 103 deletions

View File

@@ -0,0 +1,181 @@
import { useContext, useEffect } from 'react';
import { GetServerSideProps, NextPage } from 'next';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { SubmitHandler, useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import toast from 'react-hot-toast';
import withPageAuthRequired from '@/util/withPageAuthRequired';
import createErrorToast from '@/util/createErrorToast';
import UserContext from '@/contexts/UserContext';
import UserAvatar from '@/components/Account/UserAvatar';
import UpdateProfileForm from '@/components/Account/UpdateProfileForm';
import useGetUsersFollowedByUser from '@/hooks/data-fetching/user-follows/useGetUsersFollowedByUser';
import useGetUsersFollowingUser from '@/hooks/data-fetching/user-follows/useGetUsersFollowingUser';
import UpdateProfileSchema from '@/services/User/schema/UpdateProfileSchema';
import sendUpdateUserAvatarRequest from '@/requests/Account/sendUpdateUserAvatarRequest';
import sendUpdateUserProfileRequest from '@/requests/Account/sendUpdateUserProfileRequest.ts';
import Spinner from '@/components/ui/Spinner';
const ProfilePage: NextPage = () => {
const { user, mutate: mutateUser } = useContext(UserContext);
const {
register,
handleSubmit,
setValue,
formState: { errors, isSubmitting },
watch,
} = useForm<z.infer<typeof UpdateProfileSchema>>({
resolver: zodResolver(UpdateProfileSchema),
});
useEffect(() => {
if (!user || !user.bio) {
return;
}
setValue('bio', user.bio);
}, [user, setValue]);
const router = useRouter();
const onSubmit: SubmitHandler<z.infer<typeof UpdateProfileSchema>> = async (data) => {
try {
const loadingToast = toast.loading('Updating profile...');
if (!user) {
throw new Error('User is not logged in.');
}
if (data.userAvatar instanceof FileList && data.userAvatar.length === 1) {
await sendUpdateUserAvatarRequest({
userId: user.id,
file: data.userAvatar[0],
});
}
await sendUpdateUserProfileRequest({
userId: user.id,
bio: data.bio,
});
toast.remove(loadingToast);
await mutateUser!();
await router.push(`/users/${user.id}`);
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 (
<>
<Head>
<title>The Biergarten App || Update Your Profile</title>
<meta name="description" content="Update your user profile." />
</Head>
<div className="my-10 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-2 h-40 xl:my-5 xl: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="my-1 text-2xl font-bold xl:text-3xl">
{user.username}
</h2>
<div className="flex space-x-3 font-bold xl:text-lg">
<span>{followingCount} Following</span>
<span>{followerCount} Followers</span>
</div>
</div>
<div>
<p className="hyphens-auto text-center xl:text-lg">
{watch('bio') ? (
<span className="hyphens-manual">{watch('bio')}</span>
) : (
<span className="italic">Your bio will appear here.</span>
)}
</p>
</div>
</div>
<UpdateProfileForm
handleSubmit={handleSubmit}
onSubmit={onSubmit}
errors={errors}
isSubmitting={isSubmitting}
register={register}
user={user}
/>
</div>
</div>
</div>
) : (
<div className="flex h-96 items-center justify-center">
<Spinner />
</div>
)}
</div>
</>
);
};
export default ProfilePage;
export const getServerSideProps: GetServerSideProps = withPageAuthRequired();

View File

@@ -0,0 +1,80 @@
import withPageAuthRequired from '@/util/withPageAuthRequired';
import { NextPage } from 'next';
import { Tab } from '@headlessui/react';
import Head from 'next/head';
import AccountInfo from '@/components/Account/AccountInfo';
import { useContext, useReducer } from 'react';
import UserContext from '@/contexts/UserContext';
import Security from '@/components/Account/Security';
import DeleteAccount from '@/components/Account/DeleteAccount';
import accountPageReducer from '@/reducers/accountPageReducer';
import UserAvatar from '@/components/Account/UserAvatar';
import UserPosts from '@/components/Account/UserPosts';
import UpdateProfileLink from '@/components/Account/UpdateProfileLink';
const AccountPage: NextPage = () => {
const { user } = useContext(UserContext);
const [pageState, dispatch] = useReducer(accountPageReducer, {
accountInfoOpen: false,
securityOpen: false,
deleteAccountOpen: false,
});
if (!user) return null;
return (
<>
<Head>
<title>Your Account | The Biergarten App</title>
<meta
name="description"
content="Your account page. Here you can view your account information, change your settings, and view your posts."
/>
</Head>
<div className="flex flex-col items-center">
<div className="m-12 flex w-11/12 flex-col items-center justify-center space-y-3 lg:w-8/12">
<div className="flex flex-col items-center space-y-3">
<div className="mb-1 h-28 w-28">
<UserAvatar user={user} />
</div>
<div className="flex flex-col items-center space-y-1">
<p className="text-3xl font-bold">Hello, {user!.username}!</p>
<p className="text-lg">Welcome to your account page.</p>
</div>
</div>
<div className="h-full w-full">
<Tab.Group>
<Tab.List className="tabs-boxed tabs items-center justify-center rounded-2xl">
<Tab className="tab tab-md w-1/2 uppercase ui-selected:tab-active">
Account Info and Security
</Tab>
<Tab className="tab tab-md w-1/2 uppercase ui-selected:tab-active">
Your Posts
</Tab>
</Tab.List>
<Tab.Panels>
<Tab.Panel className="h-full space-y-5">
<UpdateProfileLink />
<AccountInfo pageState={pageState} dispatch={dispatch} />
<Security pageState={pageState} dispatch={dispatch} />
<DeleteAccount pageState={pageState} dispatch={dispatch} />
</Tab.Panel>
<Tab.Panel className="h-full space-y-5">
<UserPosts />
</Tab.Panel>
</Tab.Panels>
</Tab.Group>
</div>
</div>
</div>
</>
);
};
export default AccountPage;
export const getServerSideProps = withPageAuthRequired();