mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
Add like count and extracted like button out of parent
This commit is contained in:
@@ -2,50 +2,29 @@ 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 { FaRegThumbsUp, FaThumbsUp } from 'react-icons/fa';
|
||||
import BeerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
||||
|
||||
import UserContext from '@/contexts/userContext';
|
||||
import sendCheckIfUserLikesBeerPostRequest from '@/requests/sendCheckIfUserLikesBeerPostRequest';
|
||||
import sendLikeRequest from '../../requests/sendLikeRequest';
|
||||
import BeerPostLikeButton from './BeerPostLikeButton';
|
||||
|
||||
const BeerInfoHeader: FC<{ beerPost: BeerPostQueryResult }> = ({ beerPost }) => {
|
||||
const BeerInfoHeader: FC<{ beerPost: BeerPostQueryResult; initialLikeCount: number }> = ({
|
||||
beerPost,
|
||||
initialLikeCount,
|
||||
}) => {
|
||||
const createdAtDate = new Date(beerPost.createdAt);
|
||||
const [timeDistance, setTimeDistance] = useState('');
|
||||
const { user } = useContext(UserContext);
|
||||
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isLiked, setIsLiked] = useState(false);
|
||||
const [likeCount, setLikeCount] = useState(initialLikeCount);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
sendCheckIfUserLikesBeerPostRequest(beerPost.id)
|
||||
.then((currentLikeStatus) => {
|
||||
setIsLiked(currentLikeStatus);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
setLoading(false);
|
||||
});
|
||||
}, [user, beerPost.id]);
|
||||
setLikeCount(initialLikeCount);
|
||||
}, [initialLikeCount]);
|
||||
|
||||
useEffect(() => {
|
||||
setTimeDistance(formatDistanceStrict(new Date(beerPost.createdAt), new Date()));
|
||||
}, [beerPost.createdAt]);
|
||||
|
||||
const handleLike = async () => {
|
||||
try {
|
||||
await sendLikeRequest(beerPost);
|
||||
setIsLiked(!isLiked);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card flex flex-col justify-center bg-base-300">
|
||||
<div className="card-body">
|
||||
@@ -75,8 +54,8 @@ const BeerInfoHeader: FC<{ beerPost: BeerPostQueryResult }> = ({ beerPost }) =>
|
||||
|
||||
<p>{beerPost.description}</p>
|
||||
<div className="mt-5 flex justify-between">
|
||||
<div>
|
||||
<div className="mb-1">
|
||||
<div className="space-y-1">
|
||||
<div>
|
||||
<Link
|
||||
className="link-hover link text-lg font-bold"
|
||||
href={`/beers/types/${beerPost.type.id}`}
|
||||
@@ -88,31 +67,13 @@ const BeerInfoHeader: FC<{ beerPost: BeerPostQueryResult }> = ({ beerPost }) =>
|
||||
<span className="mr-4 text-lg font-medium">{beerPost.abv}% ABV</span>
|
||||
<span className="text-lg font-medium">{beerPost.ibu} IBU</span>
|
||||
</div>
|
||||
<div>
|
||||
<span>Liked by {likeCount} users</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-actions">
|
||||
<div className="card-actions items-end">
|
||||
{user && (
|
||||
<button
|
||||
type="button"
|
||||
className={`btn gap-2 rounded-2xl ${
|
||||
!isLiked ? 'btn-ghost outline' : 'btn-primary'
|
||||
}`}
|
||||
onClick={() => {
|
||||
handleLike();
|
||||
}}
|
||||
disabled={loading}
|
||||
>
|
||||
{isLiked ? (
|
||||
<>
|
||||
<FaThumbsUp className="text-2xl" />
|
||||
<span>Liked</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<FaRegThumbsUp className="text-2xl" />
|
||||
<span>Like</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
<BeerPostLikeButton beerPostId={beerPost.id} setLikeCount={setLikeCount} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
69
components/BeerById/BeerPostLikeButton.tsx
Normal file
69
components/BeerById/BeerPostLikeButton.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
import UserContext from '@/contexts/userContext';
|
||||
import sendCheckIfUserLikesBeerPostRequest from '@/requests/sendCheckIfUserLikesBeerPostRequest';
|
||||
import sendLikeRequest from '@/requests/sendLikeRequest';
|
||||
import { Dispatch, FC, SetStateAction, useContext, useEffect, useState } from 'react';
|
||||
import { FaThumbsUp, FaRegThumbsUp } from 'react-icons/fa';
|
||||
|
||||
const BeerPostLikeButton: FC<{
|
||||
beerPostId: string;
|
||||
setLikeCount: Dispatch<SetStateAction<number>>;
|
||||
}> = ({ beerPostId, setLikeCount }) => {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isLiked, setIsLiked] = useState(false);
|
||||
|
||||
const { user } = useContext(UserContext);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
sendCheckIfUserLikesBeerPostRequest(beerPostId)
|
||||
.then((currentLikeStatus) => {
|
||||
setIsLiked(currentLikeStatus);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch(() => {
|
||||
setLoading(false);
|
||||
});
|
||||
}, [user, beerPostId]);
|
||||
|
||||
const handleLike = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
await sendLikeRequest(beerPostId);
|
||||
setIsLiked(!isLiked);
|
||||
setLikeCount((prevCount) => prevCount + (isLiked ? -1 : 1));
|
||||
setLoading(false);
|
||||
} catch (error) {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`btn gap-2 rounded-2xl ${
|
||||
!isLiked ? 'btn-ghost outline' : 'btn-primary'
|
||||
}`}
|
||||
onClick={() => {
|
||||
handleLike();
|
||||
}}
|
||||
disabled={loading}
|
||||
>
|
||||
{isLiked ? (
|
||||
<>
|
||||
<FaThumbsUp className="text-2xl" />
|
||||
Liked
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<FaRegThumbsUp className="text-2xl" />
|
||||
Like
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
export default BeerPostLikeButton;
|
||||
@@ -26,6 +26,7 @@ interface BeerPageProps {
|
||||
})[];
|
||||
beerComments: BeerCommentQueryResultArrayT;
|
||||
commentsPageCount: number;
|
||||
likeCount: number;
|
||||
}
|
||||
|
||||
const BeerByIdPage: NextPage<BeerPageProps> = ({
|
||||
@@ -33,6 +34,7 @@ const BeerByIdPage: NextPage<BeerPageProps> = ({
|
||||
beerRecommendations,
|
||||
beerComments,
|
||||
commentsPageCount,
|
||||
likeCount,
|
||||
}) => {
|
||||
const { user } = useContext(UserContext);
|
||||
const [comments, setComments] = useState(beerComments);
|
||||
@@ -66,7 +68,7 @@ const BeerByIdPage: NextPage<BeerPageProps> = ({
|
||||
|
||||
<div className="my-12 flex w-full items-center justify-center ">
|
||||
<div className="w-11/12 space-y-3 lg:w-9/12">
|
||||
<BeerInfoHeader beerPost={beerPost} />
|
||||
<BeerInfoHeader beerPost={beerPost} initialLikeCount={likeCount} />
|
||||
<div className="mt-4 flex flex-col space-y-3 sm:flex-row sm:space-y-0 sm:space-x-3">
|
||||
<div className="w-full space-y-3 sm:w-[60%]">
|
||||
<div className="card h-96 bg-base-300">
|
||||
@@ -153,12 +155,16 @@ export const getServerSideProps: GetServerSideProps<BeerPageProps> = async (cont
|
||||
where: { beerPostId: beerPost.id },
|
||||
});
|
||||
const pageCount = numberOfPosts ? Math.ceil(numberOfPosts / pageSize) : 0;
|
||||
const likeCount = await DBClient.instance.beerPostLike.count({
|
||||
where: { beerPostId: beerPost.id },
|
||||
});
|
||||
|
||||
const props = {
|
||||
beerPost: JSON.parse(JSON.stringify(beerPost)),
|
||||
beerRecommendations: JSON.parse(JSON.stringify(beerRecommendations)),
|
||||
beerComments: JSON.parse(JSON.stringify(beerComments)),
|
||||
commentsPageCount: JSON.parse(JSON.stringify(pageCount)),
|
||||
likeCount: JSON.parse(JSON.stringify(likeCount)),
|
||||
};
|
||||
|
||||
return { props };
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import BeerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
|
||||
const sendLikeRequest = async (beerPost: BeerPostQueryResult) => {
|
||||
const response = await fetch(`/api/beers/${beerPost.id}/like`, {
|
||||
const sendLikeRequest = async (beerPostId: string) => {
|
||||
const response = await fetch(`/api/beers/${beerPostId}/like`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
|
||||
@@ -4,7 +4,7 @@ export const BeerCommentQueryResult = z.object({
|
||||
id: z.string().uuid(),
|
||||
content: z.string().min(1).max(300),
|
||||
rating: z.number().int().min(1).max(5),
|
||||
createdAt: z.date().or(z.string().datetime()),
|
||||
createdAt: z.coerce.date(),
|
||||
postedBy: z.object({
|
||||
id: z.string().uuid(),
|
||||
username: z.string().min(1).max(50),
|
||||
|
||||
@@ -3,20 +3,14 @@ import { z } from 'zod';
|
||||
const BeerCommentValidationSchema = z.object({
|
||||
content: z
|
||||
.string()
|
||||
.min(1, {
|
||||
message: 'Comment must not be empty.',
|
||||
})
|
||||
.max(300, {
|
||||
message: 'Comment must be less than 300 characters.',
|
||||
}),
|
||||
.min(1, { message: 'Comment must not be empty.' })
|
||||
.max(300, { message: 'Comment must be less than 300 characters.' }),
|
||||
rating: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1, { message: 'Rating must be greater than 1.' })
|
||||
.max(5, { message: 'Rating must be less than 5.' }),
|
||||
beerPostId: z.string().uuid({
|
||||
message: 'Beer post ID must be a valid UUID.',
|
||||
}),
|
||||
beerPostId: z.string().uuid({ message: 'Beer post ID must be a valid UUID.' }),
|
||||
});
|
||||
|
||||
export default BeerCommentValidationSchema;
|
||||
|
||||
Reference in New Issue
Block a user