Add custom hooks for time distance and retrieving like count

Documentation added to all custom hooks
This commit is contained in:
Aaron William Po
2023-04-03 23:32:32 -04:00
parent 801a3c8ad3
commit a4362a531c
13 changed files with 174 additions and 53 deletions

View File

@@ -1,33 +1,26 @@
import Link from 'next/link';
import formatDistanceStrict from 'date-fns/formatDistanceStrict';
import format from 'date-fns/format';
import { FC, useContext, useEffect, useState } from 'react';
import { FC, useContext } from 'react';
import UserContext from '@/contexts/userContext';
import { FaRegEdit } from 'react-icons/fa';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import { z } from 'zod';
import useGetLikeCount from '@/hooks/useGetLikeCount';
import useTimeDistance from '@/hooks/useTimeDistance';
import BeerPostLikeButton from './BeerPostLikeButton';
const BeerInfoHeader: FC<{
beerPost: z.infer<typeof beerPostQueryResult>;
initialLikeCount: number;
}> = ({ beerPost, initialLikeCount }) => {
const createdAtDate = new Date(beerPost.createdAt);
const [timeDistance, setTimeDistance] = useState('');
const { user } = useContext(UserContext);
}> = ({ beerPost }) => {
const createdAt = new Date(beerPost.createdAt);
const timeDistance = useTimeDistance(createdAt);
const [likeCount, setLikeCount] = useState(initialLikeCount);
const { user } = useContext(UserContext);
const idMatches = user && beerPost.postedBy.id === user.id;
const isPostOwner = !!(user && idMatches);
useEffect(() => {
setLikeCount(initialLikeCount);
}, [initialLikeCount]);
useEffect(() => {
setTimeDistance(formatDistanceStrict(new Date(beerPost.createdAt), new Date()));
}, [beerPost.createdAt]);
const { likeCount, mutate } = useGetLikeCount(beerPost.id);
return (
<main className="card flex flex-col justify-center bg-base-300">
@@ -62,12 +55,14 @@ const BeerInfoHeader: FC<{
<Link href={`/users/${beerPost.postedBy.id}`} className="link-hover link">
{`${beerPost.postedBy.username} `}
</Link>
{timeDistance && (
<span
className="tooltip tooltip-right"
data-tip={format(createdAtDate, 'MM/dd/yyyy')}
data-tip={format(createdAt, 'MM/dd/yyyy')}
>
{`${timeDistance} ago`}
</span>
)}
</h3>
<p>{beerPost.description}</p>
@@ -86,15 +81,15 @@ const BeerInfoHeader: FC<{
<span className="text-lg font-medium">{beerPost.ibu} IBU</span>
</div>
<div>
{likeCount && (
<span>
Liked by {likeCount} user{likeCount !== 1 && 's'}
</span>
)}
</div>
</div>
<div className="card-actions items-end">
{user && (
<BeerPostLikeButton beerPostId={beerPost.id} setLikeCount={setLikeCount} />
)}
{user && <BeerPostLikeButton beerPostId={beerPost.id} mutateCount={mutate} />}
</div>
</div>
</article>

View File

@@ -1,12 +1,13 @@
import useCheckIfUserLikesBeerPost from '@/hooks/useCheckIfUserLikesBeerPost';
import sendLikeRequest from '@/requests/sendLikeRequest';
import { Dispatch, FC, SetStateAction, useState } from 'react';
import { FC, useState } from 'react';
import { FaThumbsUp, FaRegThumbsUp } from 'react-icons/fa';
import { KeyedMutator } from 'swr';
const BeerPostLikeButton: FC<{
beerPostId: string;
setLikeCount: Dispatch<SetStateAction<number>>;
}> = ({ beerPostId, setLikeCount }) => {
mutateCount: KeyedMutator<number>;
}> = ({ beerPostId, mutateCount }) => {
const { isLiked, mutate: mutateLikeStatus } = useCheckIfUserLikesBeerPost(beerPostId);
const [loading, setLoading] = useState(false);
@@ -14,7 +15,7 @@ const BeerPostLikeButton: FC<{
try {
setLoading(true);
await sendLikeRequest(beerPostId);
setLikeCount((prevCount) => prevCount + (isLiked ? -1 : 1));
mutateCount();
mutateLikeStatus();
setLoading(false);
} catch (e) {

View File

@@ -1,8 +1,9 @@
import UserContext from '@/contexts/userContext';
import useTimeDistance from '@/hooks/useTimeDistance';
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
import { format, formatDistanceStrict } from 'date-fns';
import { format } from 'date-fns';
import Link from 'next/link';
import { useContext, useEffect, useState } from 'react';
import { useContext } from 'react';
import { Rating } from 'react-daisyui';
import { FaEllipsisH } from 'react-icons/fa';
@@ -63,12 +64,9 @@ const CommentCardBody: React.FC<{
pageCount: number;
}>;
}> = ({ comment, mutate }) => {
const [timeDistance, setTimeDistance] = useState('');
const { user } = useContext(UserContext);
useEffect(() => {
setTimeDistance(formatDistanceStrict(new Date(comment.createdAt), new Date()));
}, [comment.createdAt]);
const timeDistance = useTimeDistance(new Date(comment.createdAt));
return (
<div className="card-body h-64">

View File

@@ -14,7 +14,6 @@ const BeerIndexPaginationBar: FC<PaginationProps> = ({ pageCount, pageNum }) =>
className={`btn ${pageNum === 1 ? 'btn-disabled' : ''}`}
href={{ pathname: '/beers', query: { page_num: pageNum - 1 } }}
scroll={false}
prefetch={true}
>
«
</Link>
@@ -23,7 +22,6 @@ const BeerIndexPaginationBar: FC<PaginationProps> = ({ pageCount, pageNum }) =>
className={`btn ${pageNum === pageCount ? 'btn-disabled' : ''}`}
href={{ pathname: '/beers', query: { page_num: pageNum + 1 } }}
scroll={false}
prefetch={true}
>
»
</Link>

View File

@@ -9,6 +9,17 @@ interface UseBeerPostCommentsProps {
pageSize: number;
}
/**
* A custom React hook that fetches comments for a specific beer post.
*
* @param props - The props object.
* @param props.pageNum - The page number of the comments to fetch.
* @param props.id - The ID of the beer post to fetch comments for.
* @param props.pageSize - The number of comments to fetch per page.
* @returns An object containing the fetched comments, the total number of comment pages,
* a boolean indicating if the request is currently loading, and a function to mutate
* the data.
*/
const useBeerPostComments = ({ pageNum, id, pageSize }: UseBeerPostCommentsProps) => {
const { data, error, isLoading, mutate } = useSWR(
`/api/beers/${id}/comments?page_num=${pageNum}&page_size=${pageSize}`,

View File

@@ -1,7 +1,14 @@
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import useSWR from 'swr';
import { z } from 'zod';
/**
* A custom React hook that searches for beer posts that match a given query string.
*
* @param query The search query string to match beer posts against.
* @returns An object containing an array of search results matching the query, an error
* object if an error occurred during the search, and a boolean indicating if the
* request is currently loading.
*/
const useBeerPostSearch = (query: string | undefined) => {
const { data, isLoading, error } = useSWR(
`/api/beers/search?search=${query}`,

View File

@@ -4,6 +4,17 @@ import { useContext } from 'react';
import useSWR from 'swr';
import { z } from 'zod';
/**
* A custom React hook that checks if the current user has liked a beer post by fetching
* data from the server.
*
* @param beerPostId The ID of the beer post to check for likes.
* @returns An object containing a boolean indicating if the user has liked the beer post,
* an error object if an error occurred during the request, and a boolean indicating if
* the request is currently loading.
* @throws When the user is not logged in, the server returns an error status code, or if
* the response data fails to validate against the expected schema.
*/
const useCheckIfUserLikesBeerPost = (beerPostId: string) => {
const { user } = useContext(UserContext);
const { data, error, isLoading, mutate } = useSWR(

48
hooks/useGetLikeCount.ts Normal file
View File

@@ -0,0 +1,48 @@
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { z } from 'zod';
import useSWR from 'swr';
/**
* Custom hook to fetch the like count for a beer post from the server.
*
* @param beerPostId - The ID of the beer post to fetch the like count for.
* @returns An object with the current like count, as well as metadata about the current
* state of the request.
*/
const useGetLikeCount = (beerPostId: string) => {
const { error, mutate, data, isLoading } = useSWR(
`/api/beers/${beerPostId}/like`,
async (url) => {
const response = await fetch(url);
const json = await response.json();
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error('Failed to parse API response');
}
const parsedPayload = z
.object({
likeCount: z.number(),
})
.safeParse(parsed.data.payload);
if (!parsedPayload.success) {
throw new Error('Failed to parse API response payload');
}
return parsedPayload.data.likeCount;
},
);
return {
error: error as unknown,
isLoading,
mutate,
likeCount: data as number | undefined,
};
};
export default useGetLikeCount;

View File

@@ -2,7 +2,14 @@ import UserContext from '@/contexts/userContext';
import { useRouter } from 'next/router';
import { useContext } from 'react';
const useRedirectWhenLoggedIn = () => {
/**
* Custom React hook that redirects the user to the home page if they are logged in. This
* hook is used to prevent logged in users from accessing the login and signup pages. Must
* be used under the UserContext provider.
*
* @returns {void}
*/
const useRedirectWhenLoggedIn = (): void => {
const { user } = useContext(UserContext);
const router = useRouter();

20
hooks/useTimeDistance.ts Normal file
View File

@@ -0,0 +1,20 @@
import formatDistanceStrict from 'date-fns/formatDistanceStrict';
import { useState, useEffect } from 'react';
/**
* Returns the time distance between the provided date and the current time, using the
* `date-fns` `formatDistanceStrict` function. This hook ensures that the same result is
* calculated on both the server and client, preventing hydration errors.
*
* @param createdAt The date to calculate the time distance from.
* @returns The time distance between the provided date and the current time.
*/
const useTimeDistance = (createdAt: Date) => {
const [timeDistance, setTimeDistance] = useState('');
useEffect(() => {
setTimeDistance(formatDistanceStrict(createdAt, new Date()));
}, [createdAt]);
return timeDistance;
};
export default useTimeDistance;

View File

@@ -2,6 +2,15 @@ import GetUserSchema from '@/services/User/schema/GetUserSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import useSWR from 'swr';
/**
* A custom React hook that fetches the current user's data from the server.
*
* @returns An object containing the current user's data, a boolean indicating if the
* request is currently loading, and an error object if an error occurred during the
* request.
* @throws When the user is not logged in, the server returns an error status code, or if
* the response data fails to validate against the expected schema.
*/
const useUser = () => {
const {
data: user,

View File

@@ -4,13 +4,14 @@ import getBeerPostById from '@/services/BeerPost/getBeerPostById';
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import { createRouter } from 'next-connect';
import { z } from 'zod';
import { NextApiResponse } from 'next';
import { NextApiRequest, NextApiResponse } from 'next';
import ServerError from '@/config/util/ServerError';
import createBeerPostLike from '@/services/BeerPostLike/createBeerPostLike';
import removeBeerPostLikeById from '@/services/BeerPostLike/removeBeerPostLikeById';
import findBeerPostLikeById from '@/services/BeerPostLike/findBeerPostLikeById';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import DBClient from '@/prisma/DBClient';
const sendLikeRequest = async (
req: UserExtendedNextApiRequest,
@@ -43,6 +44,24 @@ const sendLikeRequest = async (
res.status(200).json(jsonResponse);
};
const getLikeCount = async (
req: NextApiRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const id = req.query.id as string;
const likes = await DBClient.instance.beerPostLike.count({
where: { beerPostId: id },
});
res.status(200).json({
success: true,
message: 'Successfully retrieved like count.',
statusCode: 200,
payload: { likeCount: likes },
});
};
const router = createRouter<
UserExtendedNextApiRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
@@ -54,5 +73,11 @@ router.post(
sendLikeRequest,
);
router.get(
validateRequest({ querySchema: z.object({ id: z.string().uuid() }) }),
getLikeCount,
);
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -12,7 +12,6 @@ import getBeerRecommendations from '@/services/BeerPost/getBeerRecommendations';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import { BeerPost } from '@prisma/client';
import getBeerPostLikeCount from '@/services/BeerPostLike/getBeerPostLikeCount';
import { z } from 'zod';
@@ -22,14 +21,9 @@ interface BeerPageProps {
brewery: { id: string; name: string };
beerImages: { id: string; alt: string; url: string }[];
})[];
likeCount: number;
}
const BeerByIdPage: NextPage<BeerPageProps> = ({
beerPost,
beerRecommendations,
likeCount,
}) => {
const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost, beerRecommendations }) => {
return (
<Layout>
<Head>
@@ -49,7 +43,7 @@ const BeerByIdPage: NextPage<BeerPageProps> = ({
<div className="my-12 flex w-full items-center justify-center ">
<div className="w-11/12 space-y-3 xl:w-9/12">
<BeerInfoHeader beerPost={beerPost} initialLikeCount={likeCount} />
<BeerInfoHeader beerPost={beerPost} />
<div className="mt-4 flex flex-col space-y-3 md:flex-row md:space-y-0 md:space-x-3">
<BeerPostCommentsSection beerPost={beerPost} />
<div className="md:w-[40%]">
@@ -73,12 +67,9 @@ export const getServerSideProps: GetServerSideProps<BeerPageProps> = async (cont
const { type, brewery, id } = beerPost;
const beerRecommendations = await getBeerRecommendations({ type, brewery, id });
const likeCount = await getBeerPostLikeCount(beerPost.id);
const props = {
beerPost: JSON.parse(JSON.stringify(beerPost)),
beerRecommendations: JSON.parse(JSON.stringify(beerRecommendations)),
likeCount: JSON.parse(JSON.stringify(likeCount)),
};
return { props };