mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
Merge pull request #20 from aaronpo97/infinite-comment-scroll
Feature: infinite comment scroll
This commit is contained in:
@@ -8,9 +8,7 @@ import { Rating } from 'react-daisyui';
|
|||||||
import { useForm, SubmitHandler } from 'react-hook-form';
|
import { useForm, SubmitHandler } from 'react-hook-form';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
import { KeyedMutator } from 'swr';
|
import useBeerPostComments from '@/hooks/useBeerPostComments';
|
||||||
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
|
|
||||||
import { useRouter } from 'next/router';
|
|
||||||
import Button from '../ui/forms/Button';
|
import Button from '../ui/forms/Button';
|
||||||
import FormError from '../ui/forms/FormError';
|
import FormError from '../ui/forms/FormError';
|
||||||
import FormInfo from '../ui/forms/FormInfo';
|
import FormInfo from '../ui/forms/FormInfo';
|
||||||
@@ -20,10 +18,7 @@ import FormTextArea from '../ui/forms/FormTextArea';
|
|||||||
|
|
||||||
interface BeerCommentFormProps {
|
interface BeerCommentFormProps {
|
||||||
beerPost: z.infer<typeof beerPostQueryResult>;
|
beerPost: z.infer<typeof beerPostQueryResult>;
|
||||||
mutate: KeyedMutator<{
|
mutate: ReturnType<typeof useBeerPostComments>['mutate'];
|
||||||
comments: z.infer<typeof BeerCommentQueryResult>[];
|
|
||||||
pageCount: number;
|
|
||||||
}>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const BeerCommentForm: FunctionComponent<BeerCommentFormProps> = ({
|
const BeerCommentForm: FunctionComponent<BeerCommentFormProps> = ({
|
||||||
@@ -45,7 +40,6 @@ const BeerCommentForm: FunctionComponent<BeerCommentFormProps> = ({
|
|||||||
reset({ rating: 0, content: '' });
|
reset({ rating: 0, content: '' });
|
||||||
}, [reset]);
|
}, [reset]);
|
||||||
|
|
||||||
const router = useRouter();
|
|
||||||
const onSubmit: SubmitHandler<z.infer<typeof BeerCommentValidationSchema>> = async (
|
const onSubmit: SubmitHandler<z.infer<typeof BeerCommentValidationSchema>> = async (
|
||||||
data,
|
data,
|
||||||
) => {
|
) => {
|
||||||
@@ -56,14 +50,8 @@ const BeerCommentForm: FunctionComponent<BeerCommentFormProps> = ({
|
|||||||
rating: data.rating,
|
rating: data.rating,
|
||||||
beerPostId: beerPost.id,
|
beerPostId: beerPost.id,
|
||||||
});
|
});
|
||||||
|
await mutate();
|
||||||
reset();
|
reset();
|
||||||
|
|
||||||
const submitTasks: Promise<unknown>[] = [
|
|
||||||
router.push(`/beers/${beerPost.id}`, undefined, { scroll: false }),
|
|
||||||
mutate(),
|
|
||||||
];
|
|
||||||
|
|
||||||
await Promise.all(submitTasks);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const { errors } = formState;
|
const { errors } = formState;
|
||||||
|
|||||||
@@ -1,54 +0,0 @@
|
|||||||
import { FC } from 'react';
|
|
||||||
import Link from 'next/link';
|
|
||||||
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
|
||||||
import { z } from 'zod';
|
|
||||||
|
|
||||||
import { FaArrowLeft, FaArrowRight } from 'react-icons/fa';
|
|
||||||
|
|
||||||
interface BeerCommentsPaginationBarProps {
|
|
||||||
commentsPageNum: number;
|
|
||||||
commentsPageCount: number;
|
|
||||||
beerPost: z.infer<typeof beerPostQueryResult>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const BeerCommentsPaginationBar: FC<BeerCommentsPaginationBarProps> = ({
|
|
||||||
commentsPageNum,
|
|
||||||
commentsPageCount,
|
|
||||||
beerPost,
|
|
||||||
}) => (
|
|
||||||
<div className="flex items-center justify-center" id="comments-pagination">
|
|
||||||
<div className="btn-group">
|
|
||||||
<Link
|
|
||||||
className={`btn-ghost btn ${
|
|
||||||
commentsPageNum === 1
|
|
||||||
? 'btn-disabled pointer-events-none'
|
|
||||||
: 'pointer-events-auto'
|
|
||||||
}`}
|
|
||||||
href={{
|
|
||||||
pathname: `/beers/${beerPost.id}`,
|
|
||||||
query: { comments_page: commentsPageNum - 1 },
|
|
||||||
}}
|
|
||||||
scroll={false}
|
|
||||||
>
|
|
||||||
<FaArrowLeft />
|
|
||||||
</Link>
|
|
||||||
<button className="btn-ghost btn pointer-events-none">{commentsPageNum}</button>
|
|
||||||
<Link
|
|
||||||
className={`btn-ghost btn ${
|
|
||||||
commentsPageNum === commentsPageCount
|
|
||||||
? 'btn-disabled pointer-events-none'
|
|
||||||
: 'pointer-events-auto'
|
|
||||||
}`}
|
|
||||||
href={{
|
|
||||||
pathname: `/beers/${beerPost.id}`,
|
|
||||||
query: { comments_page: commentsPageNum + 1 },
|
|
||||||
}}
|
|
||||||
scroll={false}
|
|
||||||
>
|
|
||||||
<FaArrowRight />
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
export default BeerCommentsPaginationBar;
|
|
||||||
@@ -3,33 +3,58 @@ import UserContext from '@/contexts/userContext';
|
|||||||
|
|
||||||
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
||||||
|
|
||||||
import { FC, useContext } from 'react';
|
import { FC, MutableRefObject, useContext, useRef } from 'react';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import useBeerPostComments from '@/hooks/useBeerPostComments';
|
import useBeerPostComments from '@/hooks/useBeerPostComments';
|
||||||
import { useRouter } from 'next/router';
|
import { useRouter } from 'next/router';
|
||||||
|
import { useInView } from 'react-intersection-observer';
|
||||||
import BeerCommentForm from './BeerCommentForm';
|
import BeerCommentForm from './BeerCommentForm';
|
||||||
import BeerCommentsPaginationBar from './BeerPostCommentsPaginationBar';
|
|
||||||
import CommentCardBody from './CommentCardBody';
|
import CommentCardBody from './CommentCardBody';
|
||||||
import NoCommentsCard from './NoCommentsCard';
|
import NoCommentsCard from './NoCommentsCard';
|
||||||
import CommentLoadingCardBody from './CommentLoadingCardBody';
|
import CommentLoadingCardBody from './CommentLoadingCardBody';
|
||||||
|
import Spinner from '../ui/Spinner';
|
||||||
|
|
||||||
interface BeerPostCommentsSectionProps {
|
interface BeerPostCommentsSectionProps {
|
||||||
beerPost: z.infer<typeof beerPostQueryResult>;
|
beerPost: z.infer<typeof beerPostQueryResult>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const LoadingComponent: FC<{ length: number }> = ({ length }) => {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{Array.from({ length }).map((_, i) => (
|
||||||
|
<CommentLoadingCardBody key={i} />
|
||||||
|
))}
|
||||||
|
<div className="p-1">
|
||||||
|
<Spinner size="sm" />
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost }) => {
|
const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost }) => {
|
||||||
const { user } = useContext(UserContext);
|
const { user } = useContext(UserContext);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { id } = beerPost;
|
const { id } = beerPost;
|
||||||
const pageNum = parseInt(router.query.comments_page as string, 10) || 1;
|
const pageNum = parseInt(router.query.comments_page as string, 10) || 1;
|
||||||
const pageSize = 5;
|
const PAGE_SIZE = 6;
|
||||||
|
|
||||||
const { comments, commentsPageCount, isLoading, mutate } = useBeerPostComments({
|
const { comments, isLoading, mutate, setSize, size, isLoadingMore, isAtEnd } =
|
||||||
id,
|
useBeerPostComments({
|
||||||
pageNum,
|
id,
|
||||||
pageSize,
|
pageNum,
|
||||||
|
pageSize: PAGE_SIZE,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { ref } = useInView({
|
||||||
|
delay: 3000,
|
||||||
|
onChange: (visible) => {
|
||||||
|
if (!visible || isAtEnd) return;
|
||||||
|
setSize(size + 1);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const sectionRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
|
||||||
return (
|
return (
|
||||||
<div className="w-full space-y-3 md:w-[60%]">
|
<div className="w-full space-y-3 md:w-[60%]">
|
||||||
<div className="card h-96 bg-base-300">
|
<div className="card h-96 bg-base-300">
|
||||||
@@ -44,17 +69,37 @@ const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost })
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{comments && !!comments.length && !!commentsPageCount && !isLoading && (
|
{comments && !!comments.length && !isLoading && (
|
||||||
<div className="card bg-base-300 pb-6">
|
<div className="card bg-base-300 pb-6" ref={sectionRef}>
|
||||||
{comments.map((comment) => (
|
{comments.map((comment, index) => {
|
||||||
<CommentCardBody key={comment.id} comment={comment} mutate={mutate} />
|
const isLastComment = index === comments.length - 1;
|
||||||
))}
|
|
||||||
|
|
||||||
<BeerCommentsPaginationBar
|
return (
|
||||||
commentsPageNum={pageNum}
|
<div ref={isLastComment ? ref : undefined} key={comment.id}>
|
||||||
commentsPageCount={commentsPageCount}
|
<CommentCardBody comment={comment} mutate={mutate} />
|
||||||
beerPost={beerPost}
|
</div>
|
||||||
/>
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{!!isLoadingMore && (
|
||||||
|
<div>
|
||||||
|
<LoadingComponent length={Math.floor(PAGE_SIZE / 2)} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isAtEnd && (
|
||||||
|
<div className="flex h-10 items-center justify-center text-center">
|
||||||
|
<button
|
||||||
|
className="btn-ghost btn-sm btn"
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
sectionRef.current!.scrollIntoView({ behavior: 'smooth' });
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Scroll to top of comments
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -62,15 +107,7 @@ const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost })
|
|||||||
|
|
||||||
{isLoading && (
|
{isLoading && (
|
||||||
<div className="card bg-base-300 pb-6">
|
<div className="card bg-base-300 pb-6">
|
||||||
{Array.from({ length: pageSize }).map((_, i) => (
|
<LoadingComponent length={PAGE_SIZE} />
|
||||||
<CommentLoadingCardBody key={i} />
|
|
||||||
))}
|
|
||||||
|
|
||||||
<BeerCommentsPaginationBar
|
|
||||||
commentsPageNum={pageNum}
|
|
||||||
commentsPageCount={20}
|
|
||||||
beerPost={beerPost}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,11 +2,12 @@ import useCheckIfUserLikesBeerPost from '@/hooks/useCheckIfUserLikesBeerPost';
|
|||||||
import sendLikeRequest from '@/requests/sendLikeRequest';
|
import sendLikeRequest from '@/requests/sendLikeRequest';
|
||||||
import { FC, useEffect, useState } from 'react';
|
import { FC, useEffect, useState } from 'react';
|
||||||
import { FaThumbsUp, FaRegThumbsUp } from 'react-icons/fa';
|
import { FaThumbsUp, FaRegThumbsUp } from 'react-icons/fa';
|
||||||
import { KeyedMutator } from 'swr';
|
|
||||||
|
import useGetLikeCount from '@/hooks/useGetLikeCount';
|
||||||
|
|
||||||
const BeerPostLikeButton: FC<{
|
const BeerPostLikeButton: FC<{
|
||||||
beerPostId: string;
|
beerPostId: string;
|
||||||
mutateCount: KeyedMutator<number>;
|
mutateCount: ReturnType<typeof useGetLikeCount>['mutate'];
|
||||||
}> = ({ beerPostId, mutateCount }) => {
|
}> = ({ beerPostId, mutateCount }) => {
|
||||||
const { isLiked, mutate: mutateLikeStatus } = useCheckIfUserLikesBeerPost(beerPostId);
|
const { isLiked, mutate: mutateLikeStatus } = useCheckIfUserLikesBeerPost(beerPostId);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|||||||
@@ -1,22 +1,23 @@
|
|||||||
import UserContext from '@/contexts/userContext';
|
import UserContext from '@/contexts/userContext';
|
||||||
|
import useBeerPostComments from '@/hooks/useBeerPostComments';
|
||||||
import useTimeDistance from '@/hooks/useTimeDistance';
|
import useTimeDistance from '@/hooks/useTimeDistance';
|
||||||
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
|
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
|
||||||
import format from 'date-fns/format';
|
import format from 'date-fns/format';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { useContext } from 'react';
|
import { FC, useContext } from 'react';
|
||||||
import { Rating } from 'react-daisyui';
|
import { Rating } from 'react-daisyui';
|
||||||
|
|
||||||
import { FaEllipsisH } from 'react-icons/fa';
|
import { FaEllipsisH } from 'react-icons/fa';
|
||||||
import { KeyedMutator } from 'swr';
|
import { useInView } from 'react-intersection-observer';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
const CommentCardDropdown: React.FC<{
|
interface CommentCardProps {
|
||||||
comment: z.infer<typeof BeerCommentQueryResult>;
|
comment: z.infer<typeof BeerCommentQueryResult>;
|
||||||
mutate: KeyedMutator<{
|
mutate: ReturnType<typeof useBeerPostComments>['mutate'];
|
||||||
comments: z.infer<typeof BeerCommentQueryResult>[];
|
ref?: ReturnType<typeof useInView>['ref'];
|
||||||
pageCount: number;
|
}
|
||||||
}>;
|
|
||||||
}> = ({ comment, mutate }) => {
|
const CommentCardDropdown: FC<CommentCardProps> = ({ comment, mutate }) => {
|
||||||
const { user } = useContext(UserContext);
|
const { user } = useContext(UserContext);
|
||||||
|
|
||||||
const isCommentOwner = user?.id === comment.postedBy.id;
|
const isCommentOwner = user?.id === comment.postedBy.id;
|
||||||
@@ -42,34 +43,25 @@ const CommentCardDropdown: React.FC<{
|
|||||||
tabIndex={0}
|
tabIndex={0}
|
||||||
className="dropdown-content menu rounded-box w-52 bg-base-100 p-2 shadow"
|
className="dropdown-content menu rounded-box w-52 bg-base-100 p-2 shadow"
|
||||||
>
|
>
|
||||||
{isCommentOwner ? (
|
<li>
|
||||||
<li>
|
{isCommentOwner ? (
|
||||||
<button onClick={handleDelete}>Delete</button>
|
<button onClick={handleDelete}>Delete</button>
|
||||||
</li>
|
) : (
|
||||||
) : (
|
|
||||||
<li>
|
|
||||||
<button>Report</button>
|
<button>Report</button>
|
||||||
</li>
|
)}
|
||||||
)}
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const CommentCardBody: React.FC<{
|
const CommentCardBody: FC<CommentCardProps> = ({ comment, mutate, ref }) => {
|
||||||
comment: z.infer<typeof BeerCommentQueryResult>;
|
|
||||||
|
|
||||||
mutate: KeyedMutator<{
|
|
||||||
comments: z.infer<typeof BeerCommentQueryResult>[];
|
|
||||||
pageCount: number;
|
|
||||||
}>;
|
|
||||||
}> = ({ comment, mutate }) => {
|
|
||||||
const { user } = useContext(UserContext);
|
const { user } = useContext(UserContext);
|
||||||
|
|
||||||
const timeDistance = useTimeDistance(new Date(comment.createdAt));
|
const timeDistance = useTimeDistance(new Date(comment.createdAt));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="card-body animate-in fade-in-10">
|
<div className="card-body animate-in fade-in-10" ref={ref}>
|
||||||
<div className="flex flex-col justify-between sm:flex-row">
|
<div className="flex flex-col justify-between sm:flex-row">
|
||||||
<div>
|
<div>
|
||||||
<h3 className="font-semibold sm:text-2xl">
|
<h3 className="font-semibold sm:text-2xl">
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
const CommentLoadingCardBody = () => {
|
const CommentLoadingCardBody = () => {
|
||||||
return (
|
return (
|
||||||
<div className="animate card-body h-64 fade-in-10">
|
<div className="animate card-body h-52 fade-in-10">
|
||||||
<div className="flex animate-pulse space-x-4 slide-in-from-top">
|
<div className="flex animate-pulse space-x-4 slide-in-from-top">
|
||||||
<div className="flex-1 space-y-4 py-1">
|
<div className="flex-1 space-y-4 py-1">
|
||||||
<div className="h-4 w-3/4 rounded bg-base-100" />
|
<div className="h-4 w-3/4 rounded bg-base-100" />
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="h-4 rounded bg-base-100" />
|
<div className="h-4 rounded bg-base-100" />
|
||||||
<div className="h-4 w-5/6 rounded bg-base-100" />
|
<div className="h-4 w-11/12 rounded bg-base-100" />
|
||||||
|
<div className="h-4 w-10/12 rounded bg-base-100" />
|
||||||
|
<div className="h-4 w-11/12 rounded bg-base-100" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ const Navbar = () => {
|
|||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-none lg:hidden">
|
<div className="flex-none lg:hidden">
|
||||||
<div className="dropdown-end dropdown">
|
<div className="dropdown dropdown-end">
|
||||||
<label tabIndex={0} className="btn-ghost btn-circle btn">
|
<label tabIndex={0} className="btn-ghost btn-circle btn">
|
||||||
<span className="w-10 rounded-full">
|
<span className="w-10 rounded-full">
|
||||||
<svg
|
<svg
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ interface SpinnerProps {
|
|||||||
|
|
||||||
const Spinner: FC<SpinnerProps> = ({ size = 'md' }) => {
|
const Spinner: FC<SpinnerProps> = ({ size = 'md' }) => {
|
||||||
const spinnerWidths: Record<NonNullable<SpinnerProps['size']>, `w-[${number}px]`> = {
|
const spinnerWidths: Record<NonNullable<SpinnerProps['size']>, `w-[${number}px]`> = {
|
||||||
xs: 'w-[10px]',
|
xs: 'w-[45px]',
|
||||||
sm: 'w-[20px]',
|
sm: 'w-[60px]',
|
||||||
md: 'w-[100px]',
|
md: 'w-[100px]',
|
||||||
lg: 'w-[150px]',
|
lg: 'w-[150px]',
|
||||||
xl: 'w-[200px]',
|
xl: 'w-[200px]',
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
|
import useUser from '@/hooks/useUser';
|
||||||
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
||||||
import { createContext } from 'react';
|
import { createContext } from 'react';
|
||||||
import { KeyedMutator } from 'swr';
|
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
const UserContext = createContext<{
|
const UserContext = createContext<{
|
||||||
user?: z.infer<typeof GetUserSchema>;
|
user?: z.infer<typeof GetUserSchema>;
|
||||||
error?: unknown;
|
error?: unknown;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
mutate?: KeyedMutator<z.infer<typeof GetUserSchema>>;
|
mutate?: ReturnType<typeof useUser>['mutate'];
|
||||||
}>({ isLoading: true });
|
}>({ isLoading: true });
|
||||||
|
|
||||||
export default UserContext;
|
export default UserContext;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
|
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
|
||||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import useSWR from 'swr';
|
import useSWRInfinite from 'swr/infinite';
|
||||||
|
|
||||||
interface UseBeerPostCommentsProps {
|
interface UseBeerPostCommentsProps {
|
||||||
pageNum: number;
|
pageNum: number;
|
||||||
@@ -20,36 +20,50 @@ interface UseBeerPostCommentsProps {
|
|||||||
* a boolean indicating if the request is currently loading, and a function to mutate
|
* a boolean indicating if the request is currently loading, and a function to mutate
|
||||||
* the data.
|
* the data.
|
||||||
*/
|
*/
|
||||||
const useBeerPostComments = ({ pageNum, id, pageSize }: UseBeerPostCommentsProps) => {
|
const useBeerPostComments = ({ id, pageSize }: UseBeerPostCommentsProps) => {
|
||||||
const { data, error, isLoading, mutate } = useSWR(
|
const fetcher = async (url: string) => {
|
||||||
`/api/beers/${id}/comments?page_num=${pageNum}&page_size=${pageSize}`,
|
const response = await fetch(url);
|
||||||
async (url) => {
|
const json = await response.json();
|
||||||
const response = await fetch(url);
|
const count = response.headers.get('X-Total-Count');
|
||||||
const json = await response.json();
|
const parsed = APIResponseValidationSchema.safeParse(json);
|
||||||
const count = response.headers.get('X-Total-Count');
|
|
||||||
const parsed = APIResponseValidationSchema.safeParse(json);
|
|
||||||
|
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
throw new Error(parsed.error.message);
|
throw new Error(parsed.error.message);
|
||||||
}
|
}
|
||||||
const parsedPayload = z
|
const parsedPayload = z.array(BeerCommentQueryResult).safeParse(parsed.data.payload);
|
||||||
.array(BeerCommentQueryResult)
|
|
||||||
.safeParse(parsed.data.payload);
|
|
||||||
|
|
||||||
if (!parsedPayload.success) {
|
if (!parsedPayload.success) {
|
||||||
throw new Error(parsedPayload.error.message);
|
throw new Error(parsedPayload.error.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
const pageCount = Math.ceil(parseInt(count as string, 10) / pageSize);
|
const pageCount = Math.ceil(parseInt(count as string, 10) / pageSize);
|
||||||
return { comments: parsedPayload.data, pageCount };
|
return { comments: parsedPayload.data, pageCount };
|
||||||
},
|
};
|
||||||
|
|
||||||
|
const { data, error, isLoading, mutate, size, setSize } = useSWRInfinite(
|
||||||
|
(index) => `/api/beers/${id}/comments?page_num=${index + 1}&page_size=${pageSize}`,
|
||||||
|
fetcher,
|
||||||
|
{ parallel: true },
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const comments = data?.flatMap((d) => d.comments) ?? [];
|
||||||
|
const pageCount = data?.[0].pageCount ?? 0;
|
||||||
|
|
||||||
|
const isLoadingMore =
|
||||||
|
isLoading || (size > 0 && data && typeof data[size - 1] === 'undefined');
|
||||||
|
|
||||||
|
const isAtEnd = !(size < data?.[0].pageCount!);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
comments: data?.comments,
|
comments,
|
||||||
commentsPageCount: data?.pageCount,
|
|
||||||
isLoading,
|
isLoading,
|
||||||
error: error as undefined,
|
error: error as undefined,
|
||||||
mutate,
|
mutate,
|
||||||
|
size,
|
||||||
|
setSize,
|
||||||
|
isLoadingMore,
|
||||||
|
isAtEnd,
|
||||||
|
pageCount,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
15
package-lock.json
generated
15
package-lock.json
generated
@@ -35,6 +35,7 @@
|
|||||||
"react-email": "^1.9.0",
|
"react-email": "^1.9.0",
|
||||||
"react-hook-form": "^7.43.9",
|
"react-hook-form": "^7.43.9",
|
||||||
"react-icons": "^4.8.0",
|
"react-icons": "^4.8.0",
|
||||||
|
"react-intersection-observer": "^9.4.3",
|
||||||
"sparkpost": "^2.1.4",
|
"sparkpost": "^2.1.4",
|
||||||
"swr": "^2.1.2",
|
"swr": "^2.1.2",
|
||||||
"zod": "^3.21.4"
|
"zod": "^3.21.4"
|
||||||
@@ -8341,6 +8342,14 @@
|
|||||||
"react": "*"
|
"react": "*"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/react-intersection-observer": {
|
||||||
|
"version": "9.4.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/react-intersection-observer/-/react-intersection-observer-9.4.3.tgz",
|
||||||
|
"integrity": "sha512-WNRqMQvKpupr6MzecAQI0Pj0+JQong307knLP4g/nBex7kYfIaZsPpXaIhKHR+oV8z+goUbH9e10j6lGRnTzlQ==",
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/react-is": {
|
"node_modules/react-is": {
|
||||||
"version": "16.13.1",
|
"version": "16.13.1",
|
||||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
||||||
@@ -15901,6 +15910,12 @@
|
|||||||
"integrity": "sha512-N6+kOLcihDiAnj5Czu637waJqSnwlMNROzVZMhfX68V/9bu9qHaMIJC4UdozWoOk57gahFCNHwVvWzm0MTzRjg==",
|
"integrity": "sha512-N6+kOLcihDiAnj5Czu637waJqSnwlMNROzVZMhfX68V/9bu9qHaMIJC4UdozWoOk57gahFCNHwVvWzm0MTzRjg==",
|
||||||
"requires": {}
|
"requires": {}
|
||||||
},
|
},
|
||||||
|
"react-intersection-observer": {
|
||||||
|
"version": "9.4.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/react-intersection-observer/-/react-intersection-observer-9.4.3.tgz",
|
||||||
|
"integrity": "sha512-WNRqMQvKpupr6MzecAQI0Pj0+JQong307knLP4g/nBex7kYfIaZsPpXaIhKHR+oV8z+goUbH9e10j6lGRnTzlQ==",
|
||||||
|
"requires": {}
|
||||||
|
},
|
||||||
"react-is": {
|
"react-is": {
|
||||||
"version": "16.13.1",
|
"version": "16.13.1",
|
||||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
||||||
|
|||||||
@@ -38,6 +38,7 @@
|
|||||||
"react-email": "^1.9.0",
|
"react-email": "^1.9.0",
|
||||||
"react-hook-form": "^7.43.9",
|
"react-hook-form": "^7.43.9",
|
||||||
"react-icons": "^4.8.0",
|
"react-icons": "^4.8.0",
|
||||||
|
"react-intersection-observer": "^9.4.3",
|
||||||
"sparkpost": "^2.1.4",
|
"sparkpost": "^2.1.4",
|
||||||
"swr": "^2.1.2",
|
"swr": "^2.1.2",
|
||||||
"zod": "^3.21.4"
|
"zod": "^3.21.4"
|
||||||
|
|||||||
@@ -25,35 +25,37 @@ interface BeerPageProps {
|
|||||||
|
|
||||||
const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost, beerRecommendations }) => {
|
const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost, beerRecommendations }) => {
|
||||||
return (
|
return (
|
||||||
<Layout>
|
<>
|
||||||
<Head>
|
<Head>
|
||||||
<title>{beerPost.name}</title>
|
<title>{beerPost.name}</title>
|
||||||
<meta name="description" content={beerPost.description} />
|
<meta name="description" content={beerPost.description} />
|
||||||
</Head>
|
</Head>
|
||||||
<div>
|
<Layout>
|
||||||
{beerPost.beerImages[0] && (
|
<div>
|
||||||
<Image
|
{beerPost.beerImages[0] && (
|
||||||
alt={beerPost.beerImages[0].alt}
|
<Image
|
||||||
src={beerPost.beerImages[0].path}
|
alt={beerPost.beerImages[0].alt}
|
||||||
height={1080}
|
src={beerPost.beerImages[0].path}
|
||||||
width={1920}
|
height={1080}
|
||||||
className="h-[42rem] w-full object-cover"
|
width={1920}
|
||||||
/>
|
className="h-[42rem] w-full object-cover"
|
||||||
)}
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
<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 xl:w-9/12">
|
<div className="w-11/12 space-y-3 xl:w-9/12">
|
||||||
<BeerInfoHeader beerPost={beerPost} />
|
<BeerInfoHeader beerPost={beerPost} />
|
||||||
<div className="mt-4 flex flex-col space-y-3 md:flex-row md:space-x-3 md:space-y-0">
|
<div className="mt-4 flex flex-col space-y-3 md:flex-row md:space-x-3 md:space-y-0">
|
||||||
<BeerPostCommentsSection beerPost={beerPost} />
|
<BeerPostCommentsSection beerPost={beerPost} />
|
||||||
<div className="md:w-[40%]">
|
<div className="md:w-[40%]">
|
||||||
<BeerRecommendations beerRecommendations={beerRecommendations} />
|
<BeerRecommendations beerRecommendations={beerRecommendations} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Layout>
|
||||||
</Layout>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ const ProtectedPage: NextPage = () => {
|
|||||||
|
|
||||||
const isMorning = currentTime > 4 && currentTime < 12;
|
const isMorning = currentTime > 4 && currentTime < 12;
|
||||||
const isAfternoon = currentTime > 12 && currentTime < 18;
|
const isAfternoon = currentTime > 12 && currentTime < 18;
|
||||||
const isEvening = currentTime > 18 && currentTime < 24 || currentTime <4
|
const isEvening = (currentTime > 18 && currentTime < 24) || currentTime < 4;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Layout>
|
<Layout>
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ const createNewUsers = async ({ numberOfUsers }: CreateNewUsersArgs) => {
|
|||||||
|
|
||||||
// eslint-disable-next-line no-plusplus
|
// eslint-disable-next-line no-plusplus
|
||||||
for (let i = 0; i < numberOfUsers; i++) {
|
for (let i = 0; i < numberOfUsers; i++) {
|
||||||
const randomValue = crypto.randomBytes(4).toString('hex');
|
const randomValue = crypto.randomBytes(8).toString('hex');
|
||||||
const firstName = faker.name.firstName();
|
const firstName = faker.name.firstName();
|
||||||
const lastName = faker.name.lastName();
|
const lastName = faker.name.lastName();
|
||||||
const username = `${firstName[0]}.${lastName}.${randomValue}`;
|
const username = `${firstName[0]}.${lastName}.${randomValue}`;
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ import createNewUsers from './create/createNewUsers';
|
|||||||
createNewBeerTypes({ joinData: { users } }),
|
createNewBeerTypes({ joinData: { users } }),
|
||||||
]);
|
]);
|
||||||
const beerPosts = await createNewBeerPosts({
|
const beerPosts = await createNewBeerPosts({
|
||||||
numberOfPosts: 48,
|
numberOfPosts: 200,
|
||||||
joinData: { breweryPosts, beerTypes, users },
|
joinData: { breweryPosts, beerTypes, users },
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -41,11 +41,11 @@ import createNewUsers from './create/createNewUsers';
|
|||||||
breweryImages,
|
breweryImages,
|
||||||
] = await Promise.all([
|
] = await Promise.all([
|
||||||
createNewBeerPostComments({
|
createNewBeerPostComments({
|
||||||
numberOfComments: 1000,
|
numberOfComments: 45000,
|
||||||
joinData: { beerPosts, users },
|
joinData: { beerPosts, users },
|
||||||
}),
|
}),
|
||||||
createNewBreweryPostComments({
|
createNewBreweryPostComments({
|
||||||
numberOfComments: 1000,
|
numberOfComments: 45000,
|
||||||
joinData: { breweryPosts, users },
|
joinData: { breweryPosts, users },
|
||||||
}),
|
}),
|
||||||
createNewBeerPostLikes({
|
createNewBeerPostLikes({
|
||||||
|
|||||||
Reference in New Issue
Block a user