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