mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
Replace useSWR with useSWRInfinite to facilitate infinite scrolling
This commit is contained in:
@@ -8,9 +8,9 @@ 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 BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
|
|
||||||
import { useRouter } from 'next/router';
|
import { useRouter } from 'next/router';
|
||||||
|
import useBeerPostComments from '@/hooks/useBeerPostComments';
|
||||||
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';
|
||||||
@@ -18,12 +18,10 @@ import FormLabel from '../ui/forms/FormLabel';
|
|||||||
import FormSegment from '../ui/forms/FormSegment';
|
import FormSegment from '../ui/forms/FormSegment';
|
||||||
import FormTextArea from '../ui/forms/FormTextArea';
|
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> = ({
|
||||||
|
|||||||
@@ -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;
|
|
||||||
@@ -8,7 +8,7 @@ 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 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';
|
||||||
@@ -22,12 +22,13 @@ const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost })
|
|||||||
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 } =
|
||||||
|
useBeerPostComments({
|
||||||
id,
|
id,
|
||||||
pageNum,
|
pageNum,
|
||||||
pageSize,
|
pageSize: PAGE_SIZE,
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -44,17 +45,20 @@ 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">
|
||||||
{comments.map((comment) => (
|
{comments.map((comment) => (
|
||||||
<CommentCardBody key={comment.id} comment={comment} mutate={mutate} />
|
<CommentCardBody key={comment.id} comment={comment} mutate={mutate} />
|
||||||
))}
|
))}
|
||||||
|
|
||||||
<BeerCommentsPaginationBar
|
{isLoadingMore &&
|
||||||
commentsPageNum={pageNum}
|
Array.from({ length: PAGE_SIZE }).map((_, i) => (
|
||||||
commentsPageCount={commentsPageCount}
|
<CommentLoadingCardBody key={i} />
|
||||||
beerPost={beerPost}
|
))}
|
||||||
/>
|
|
||||||
|
<button type="button" onClick={() => setSize(size + 1)}>
|
||||||
|
load more
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -62,15 +66,9 @@ 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) => (
|
{Array.from({ length: PAGE_SIZE }).map((_, i) => (
|
||||||
<CommentLoadingCardBody key={i} />
|
<CommentLoadingCardBody key={i} />
|
||||||
))}
|
))}
|
||||||
|
|
||||||
<BeerCommentsPaginationBar
|
|
||||||
commentsPageNum={pageNum}
|
|
||||||
commentsPageCount={20}
|
|
||||||
beerPost={beerPost}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,11 +2,13 @@ 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);
|
||||||
@@ -30,8 +32,7 @@ const BeerPostLikeButton: FC<{
|
|||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className={`btn gap-2 rounded-2xl ${
|
className={`btn gap-2 rounded-2xl ${!isLiked ? 'btn-ghost outline' : 'btn-primary'
|
||||||
!isLiked ? 'btn-ghost outline' : 'btn-primary'
|
|
||||||
}`}
|
}`}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
handleLike();
|
handleLike();
|
||||||
|
|||||||
@@ -1,22 +1,21 @@
|
|||||||
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 { 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>[];
|
}
|
||||||
pageCount: number;
|
|
||||||
}>;
|
const CommentCardDropdown: FC<CommentCardProps> = ({ comment, mutate }) => {
|
||||||
}> = ({ 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,28 +41,26 @@ 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"
|
||||||
>
|
>
|
||||||
|
<li>
|
||||||
|
|
||||||
|
|
||||||
{isCommentOwner ? (
|
{isCommentOwner ? (
|
||||||
<li>
|
|
||||||
<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: z.infer<typeof BeerCommentQueryResult>;
|
= ({ comment, mutate }) => {
|
||||||
|
|
||||||
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));
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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,9 +20,9 @@ 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 { data, error, isLoading, mutate, size, setSize } = useSWRInfinite(
|
||||||
`/api/beers/${id}/comments?page_num=${pageNum}&page_size=${pageSize}`,
|
(index) => `/api/beers/${id}/comments?page_num=${index + 1}&page_size=${pageSize}`,
|
||||||
async (url) => {
|
async (url) => {
|
||||||
const response = await fetch(url);
|
const response = await fetch(url);
|
||||||
const json = await response.json();
|
const json = await response.json();
|
||||||
@@ -33,6 +33,7 @@ const useBeerPostComments = ({ pageNum, id, pageSize }: UseBeerPostCommentsProps
|
|||||||
throw new Error(parsed.error.message);
|
throw new Error(parsed.error.message);
|
||||||
}
|
}
|
||||||
const parsedPayload = z
|
const parsedPayload = z
|
||||||
|
|
||||||
.array(BeerCommentQueryResult)
|
.array(BeerCommentQueryResult)
|
||||||
.safeParse(parsed.data.payload);
|
.safeParse(parsed.data.payload);
|
||||||
|
|
||||||
@@ -44,12 +45,20 @@ const useBeerPostComments = ({ pageNum, id, pageSize }: UseBeerPostCommentsProps
|
|||||||
return { comments: parsedPayload.data, pageCount };
|
return { comments: parsedPayload.data, pageCount };
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const comments = data?.flatMap((d) => d.comments) ?? [];
|
||||||
|
|
||||||
|
const isLoadingMore =
|
||||||
|
isLoading || (size > 0 && data && typeof data[size - 1] === 'undefined');
|
||||||
|
|
||||||
return {
|
return {
|
||||||
comments: data?.comments,
|
comments,
|
||||||
commentsPageCount: data?.pageCount,
|
|
||||||
isLoading,
|
isLoading,
|
||||||
error: error as undefined,
|
error: error as undefined,
|
||||||
mutate,
|
mutate,
|
||||||
|
size,
|
||||||
|
setSize,
|
||||||
|
isLoadingMore,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -25,11 +25,12 @@ 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>
|
||||||
|
<Layout>
|
||||||
<div>
|
<div>
|
||||||
{beerPost.beerImages[0] && (
|
{beerPost.beerImages[0] && (
|
||||||
<Image
|
<Image
|
||||||
@@ -54,6 +55,7 @@ const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost, beerRecommendations }
|
|||||||
</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>
|
||||||
|
|||||||
Reference in New Issue
Block a user