Implement react-intersection-observer to facilitate infinite scroll

Uses react-intersection-observer to load more comments when the last of the previously loaded comments is in the viewport.
This commit is contained in:
Aaron William Po
2023-04-09 18:41:58 -04:00
parent 8981bcb4b8
commit 915adb722a
12 changed files with 157 additions and 109 deletions

View File

@@ -8,7 +8,6 @@ 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 { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import useBeerPostComments from '@/hooks/useBeerPostComments'; import useBeerPostComments from '@/hooks/useBeerPostComments';
import Button from '../ui/forms/Button'; import Button from '../ui/forms/Button';
@@ -18,10 +17,9 @@ 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: ReturnType<typeof useBeerPostComments>['mutate'] mutate: ReturnType<typeof useBeerPostComments>['mutate'];
} }
const BeerCommentForm: FunctionComponent<BeerCommentFormProps> = ({ const BeerCommentForm: FunctionComponent<BeerCommentFormProps> = ({
@@ -43,7 +41,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,
) => { ) => {
@@ -54,14 +51,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;

View File

@@ -3,20 +3,35 @@ 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 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();
@@ -24,13 +39,22 @@ const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost })
const pageNum = parseInt(router.query.comments_page as string, 10) || 1; const pageNum = parseInt(router.query.comments_page as string, 10) || 1;
const PAGE_SIZE = 6; const PAGE_SIZE = 6;
const { comments, isLoading, mutate, setSize, size, isLoadingMore } = const { comments, isLoading, mutate, setSize, size, isLoadingMore, isAtEnd } =
useBeerPostComments({ useBeerPostComments({
id, id,
pageNum, pageNum,
pageSize: PAGE_SIZE, 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">
@@ -46,19 +70,36 @@ const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost })
</div> </div>
{comments && !!comments.length && !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;
))}
{isLoadingMore && return (
Array.from({ length: PAGE_SIZE }).map((_, i) => ( <div ref={isLastComment ? ref : undefined} key={comment.id}>
<CommentLoadingCardBody key={i} /> <CommentCardBody comment={comment} mutate={mutate} />
))} </div>
);
})}
<button type="button" onClick={() => setSize(size + 1)}> {!!isLoadingMore && (
load more <div>
</button> <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>
)} )}
@@ -66,9 +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: PAGE_SIZE }).map((_, i) => ( <LoadingComponent length={PAGE_SIZE} />
<CommentLoadingCardBody key={i} />
))}
</div> </div>
)} )}
</div> </div>

View File

@@ -3,7 +3,6 @@ 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 useGetLikeCount from '@/hooks/useGetLikeCount'; import useGetLikeCount from '@/hooks/useGetLikeCount';
const BeerPostLikeButton: FC<{ const BeerPostLikeButton: FC<{
@@ -32,8 +31,9 @@ const BeerPostLikeButton: FC<{
return ( return (
<button <button
type="button" type="button"
className={`btn gap-2 rounded-2xl ${!isLiked ? 'btn-ghost outline' : 'btn-primary' className={`btn gap-2 rounded-2xl ${
}`} !isLiked ? 'btn-ghost outline' : 'btn-primary'
}`}
onClick={() => { onClick={() => {
handleLike(); handleLike();
}} }}

View File

@@ -8,11 +8,13 @@ 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 { useInView } from 'react-intersection-observer';
import { z } from 'zod'; import { z } from 'zod';
interface CommentCardProps { interface CommentCardProps {
comment: z.infer<typeof BeerCommentQueryResult>; comment: z.infer<typeof BeerCommentQueryResult>;
mutate: ReturnType<typeof useBeerPostComments>['mutate']; mutate: ReturnType<typeof useBeerPostComments>['mutate'];
ref?: ReturnType<typeof useInView>['ref'];
} }
const CommentCardDropdown: FC<CommentCardProps> = ({ comment, mutate }) => { const CommentCardDropdown: FC<CommentCardProps> = ({ comment, mutate }) => {
@@ -42,16 +44,10 @@ const CommentCardDropdown: FC<CommentCardProps> = ({ comment, mutate }) => {
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> <li>
{isCommentOwner ? ( {isCommentOwner ? (
<button onClick={handleDelete}>Delete</button> <button onClick={handleDelete}>Delete</button>
) : ( ) : (
<button>Report</button> <button>Report</button>
)} )}
</li> </li>
</ul> </ul>
@@ -59,52 +55,51 @@ const CommentCardDropdown: FC<CommentCardProps> = ({ comment, mutate }) => {
); );
}; };
const CommentCardBody: FC<CommentCardProps> const CommentCardBody: FC<CommentCardProps> = ({ comment, mutate, ref }) => {
= ({ 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">
<Link href={`/users/${comment.postedBy.id}`} className="link-hover link"> <Link href={`/users/${comment.postedBy.id}`} className="link-hover link">
{comment.postedBy.username} {comment.postedBy.username}
</Link> </Link>
</h3> </h3>
<h4 className="italic"> <h4 className="italic">
posted{' '} posted{' '}
<time <time
className="tooltip tooltip-bottom" className="tooltip tooltip-bottom"
data-tip={format(new Date(comment.createdAt), 'MM/dd/yyyy')} data-tip={format(new Date(comment.createdAt), 'MM/dd/yyyy')}
> >
{timeDistance} {timeDistance}
</time>{' '} </time>{' '}
ago ago
</h4> </h4>
</div>
{user && <CommentCardDropdown comment={comment} mutate={mutate} />}
</div> </div>
<div className="space-y-1"> {user && <CommentCardDropdown comment={comment} mutate={mutate} />}
<Rating value={comment.rating}>
{Array.from({ length: 5 }).map((val, index) => (
<Rating.Item
name="rating-1"
className="mask mask-star cursor-default"
disabled
aria-disabled
key={index}
/>
))}
</Rating>
<p>{comment.content}</p>
</div>
</div> </div>
);
}; <div className="space-y-1">
<Rating value={comment.rating}>
{Array.from({ length: 5 }).map((val, index) => (
<Rating.Item
name="rating-1"
className="mask mask-star cursor-default"
disabled
aria-disabled
key={index}
/>
))}
</Rating>
<p>{comment.content}</p>
</div>
</div>
);
};
export default CommentCardBody; export default CommentCardBody;

View File

@@ -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>

View File

@@ -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]',

View File

@@ -1,4 +1,4 @@
import useUser from '@/hooks/useUser'; 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 { z } from 'zod'; import { z } from 'zod';
@@ -7,7 +7,7 @@ const UserContext = createContext<{
user?: z.infer<typeof GetUserSchema>; user?: z.infer<typeof GetUserSchema>;
error?: unknown; error?: unknown;
isLoading: boolean; isLoading: boolean;
mutate?: ReturnType<typeof useUser>['mutate'] mutate?: ReturnType<typeof useUser>['mutate'];
}>({ isLoading: true }); }>({ isLoading: true });
export default UserContext; export default UserContext;

View File

@@ -21,36 +21,39 @@ interface UseBeerPostCommentsProps {
* the data. * the data.
*/ */
const useBeerPostComments = ({ id, pageSize }: UseBeerPostCommentsProps) => { const useBeerPostComments = ({ id, pageSize }: UseBeerPostCommentsProps) => {
const fetcher = async (url: string) => {
const response = await fetch(url);
const json = await response.json();
const count = response.headers.get('X-Total-Count');
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error(parsed.error.message);
}
const parsedPayload = z.array(BeerCommentQueryResult).safeParse(parsed.data.payload);
if (!parsedPayload.success) {
throw new Error(parsedPayload.error.message);
}
const pageCount = Math.ceil(parseInt(count as string, 10) / pageSize);
return { comments: parsedPayload.data, pageCount };
};
const { data, error, isLoading, mutate, size, setSize } = useSWRInfinite( const { data, error, isLoading, mutate, size, setSize } = useSWRInfinite(
(index) => `/api/beers/${id}/comments?page_num=${index + 1}&page_size=${pageSize}`, (index) => `/api/beers/${id}/comments?page_num=${index + 1}&page_size=${pageSize}`,
async (url) => { fetcher,
const response = await fetch(url); { parallel: true },
const json = await response.json();
const count = response.headers.get('X-Total-Count');
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error(parsed.error.message);
}
const parsedPayload = z
.array(BeerCommentQueryResult)
.safeParse(parsed.data.payload);
if (!parsedPayload.success) {
throw new Error(parsedPayload.error.message);
}
const pageCount = Math.ceil(parseInt(count as string, 10) / pageSize);
return { comments: parsedPayload.data, pageCount };
},
); );
const comments = data?.flatMap((d) => d.comments) ?? []; const comments = data?.flatMap((d) => d.comments) ?? [];
const pageCount = data?.[0].pageCount ?? 0;
const isLoadingMore = const isLoadingMore =
isLoading || (size > 0 && data && typeof data[size - 1] === 'undefined'); isLoading || (size > 0 && data && typeof data[size - 1] === 'undefined');
const isAtEnd = !(size < data?.[0].pageCount!);
return { return {
comments, comments,
isLoading, isLoading,
@@ -59,6 +62,8 @@ const useBeerPostComments = ({ id, pageSize }: UseBeerPostCommentsProps) => {
size, size,
setSize, setSize,
isLoadingMore, isLoadingMore,
isAtEnd,
pageCount,
}; };
}; };

15
package-lock.json generated
View File

@@ -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",

View File

@@ -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"

View File

@@ -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}`;

View File

@@ -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({