Skip to content

Connect, collaborate, and grow with a community of TypeScript developers

Feat/infinite scroll on comments (#212)

Filip Pitus88666ad53ed1
diff --git a/package.json b/package.json
index 36c1381d..9463322f 100644
--- a/package.json
+++ b/package.json
@@ -56,6 +56,7 @@
"react-day-picker": "^8.8.0",
"react-dom": "18.2.0",
"react-hook-form": "^7.45.0",
+ "react-intersection-observer": "^9.5.2",
"react-markdown": "^8.0.7",
"react-syntax-highlighter": "^15.5.0",
"recharts": "^2.7.2",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b2faad3b..b65faa74 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -127,6 +127,9 @@ dependencies:
react-hook-form:
specifier: ^7.45.0
version: 7.45.0([email protected])
+ react-intersection-observer:
+ specifier: ^9.5.2
+ version: 9.5.2([email protected])
react-markdown:
specifier: ^8.0.7
version: 8.0.7(@types/[email protected])([email protected])
@@ -5628,6 +5631,14 @@ packages:
react: 18.2.0
dev: false
+ resolution: {integrity: sha512-EmoV66/yvksJcGa1rdW0nDNc4I1RifDWkT50gXSFnPLYQ4xUptuDD4V7k+Rj1OgVAlww628KLGcxPXFlOkkU/Q==}
+ peerDependencies:
+ react: ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0
+ dependencies:
+ react: 18.2.0
+ dev: false
+
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
diff --git a/src/app/challenge/[id]/getChallengeRouteData.ts b/src/app/challenge/[id]/getChallengeRouteData.ts
index 37085758..25c49765 100644
--- a/src/app/challenge/[id]/getChallengeRouteData.ts
+++ b/src/app/challenge/[id]/getChallengeRouteData.ts
@@ -49,7 +49,6 @@ export async function getChallengeRouteData(id: string, session: Session | null)
},
},
comment: {
- take: 10,
orderBy: [
{
createdAt: 'desc',
diff --git a/src/app/challenge/[id]/page.tsx b/src/app/challenge/[id]/page.tsx
index 97b06d7a..a2ab320c 100644
--- a/src/app/challenge/[id]/page.tsx
+++ b/src/app/challenge/[id]/page.tsx
@@ -25,7 +25,7 @@ export default async function Challenges({ params: { id } }: Props) {
</div>
<div className="sticky bottom-0 -mx-[1px] overflow-hidden rounded-xl border border-zinc-300 border-b-background bg-background/90 shadow-[0_0_3rem_-0.25rem_#0004] backdrop-blur-sm duration-300 dark:border-zinc-700 dark:border-b-muted dark:bg-muted/90 dark:shadow-[0_0_3rem_-0.25rem_#0008]">
- <Comments challenge={challenge} />
+ <Comments challengeId={challenge.id} commentCount={challenge.comment.length} />
</div>
</div>
);
diff --git a/src/app/providers.tsx b/src/app/providers.tsx
index 0d4d9b0b..e0e8fdec 100644
--- a/src/app/providers.tsx
+++ b/src/app/providers.tsx
@@ -3,16 +3,22 @@
import { SessionProvider } from 'next-auth/react';
import { ThemeProvider } from 'next-themes';
import { TooltipProvider } from '~/components/ui/tooltip';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
interface Props {
children: React.ReactNode;
}
+
+const queryClient = new QueryClient();
+
export function Providers({ children }: Props) {
return (
- <SessionProvider>
- <ThemeProvider attribute="class">
- <TooltipProvider>{children}</TooltipProvider>
- </ThemeProvider>
- </SessionProvider>
+ <QueryClientProvider client={queryClient}>
+ <SessionProvider>
+ <ThemeProvider attribute="class">
+ <TooltipProvider>{children}</TooltipProvider>
+ </ThemeProvider>
+ </SessionProvider>
+ </QueryClientProvider>
);
}
diff --git a/src/components/challenge/comment-skeleton.tsx b/src/components/challenge/comment-skeleton.tsx
new file mode 100644
index 00000000..ae989dbb
--- /dev/null
+++ b/src/components/challenge/comment-skeleton.tsx
@@ -0,0 +1,15 @@
+export function CommentSkeleton() {
+ return (
+ <div className="flex flex-col space-y-10 px-4 py-3">
+ <div className="prose-invert flex flex-col gap-6 space-y-2 prose-h3:text-xl">
+ <div className="h-6 rounded-lg bg-zinc-300 dark:bg-zinc-700"></div>
+ <div className="h-6 rounded-lg bg-zinc-300 dark:bg-zinc-700"></div>
+ <div className="h-6 rounded-lg bg-zinc-300 dark:bg-zinc-700"></div>
+ <div className="h-6 rounded-lg bg-zinc-300 dark:bg-zinc-700"></div>
+ <div className="h-6 rounded-lg bg-zinc-300 dark:bg-zinc-700"></div>
+ <div className="h-6 rounded-lg bg-zinc-300 dark:bg-zinc-700"></div>
+ <div className="h-6 rounded-lg bg-zinc-300 dark:bg-zinc-700"></div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/challenge/comments/comment.tsx b/src/components/challenge/comments/comment.tsx
index 2e0efe35..8054cfc6 100644
--- a/src/components/challenge/comments/comment.tsx
+++ b/src/components/challenge/comments/comment.tsx
@@ -115,7 +115,7 @@ const Comment = ({ comment }: CommentProps) => {
Report
</button>
</div>
- <p>{comment.text}</p>
+ <p className="w-full break-words">{comment.text}</p>
<Dialog
open={dialogOpen}
onOpenChange={() => {
diff --git a/src/components/challenge/comments/getCommentRouteData.ts b/src/components/challenge/comments/getCommentRouteData.ts
new file mode 100644
index 00000000..f3bda685
--- /dev/null
+++ b/src/components/challenge/comments/getCommentRouteData.ts
@@ -0,0 +1,58 @@
+'use server';
+import { prisma } from '~/server/db';
+
+export type ChallengeRouteData = NonNullable<Awaited<ReturnType<typeof getInfiniteComments>>>;
+
+interface QueryParams {
+ challengeId: number;
+ take?: number;
+ lastCursor?: number;
+}
+
+export async function getInfiniteComments({ challengeId, take = 10, lastCursor }: QueryParams) {
+ const results = await prisma.challengeComment.findMany({
+ where: { challengeId },
+ include: { user: true },
+ take,
+ ...(lastCursor && {
+ skip: 1,
+ cursor: {
+ id: lastCursor,
+ },
+ }),
+ orderBy: {
+ createdAt: 'desc',
+ },
+ });
+
+ if (results.length == 0) {
+ return {
+ data: [],
+ metaData: {
+ lastCursor: null,
+ hasNextPage: false,
+ },
+ };
+ }
+
+ const lastPostInResults = results[results.length - 1];
+ const cursor = lastPostInResults?.id;
+
+ const nextPage = await prisma.challengeComment.findMany({
+ where: { challengeId },
+ include: { user: true },
+ take,
+ skip: 1,
+ cursor: {
+ id: cursor,
+ },
+ });
+
+ return {
+ data: results,
+ metaData: {
+ lastCursor: cursor,
+ hasNextPage: nextPage.length > 0,
+ },
+ };
+}
diff --git a/src/components/challenge/comments/index.tsx b/src/components/challenge/comments/index.tsx
index 8bafc3ef..8c73b1e9 100644
--- a/src/components/challenge/comments/index.tsx
+++ b/src/components/challenge/comments/index.tsx
@@ -3,24 +3,36 @@
import clsx from 'clsx';
import { ChevronDown, MessageCircle } from 'lucide-react';
import { useRouter } from 'next/navigation';
-import { useState } from 'react';
-import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';
+import { useEffect, useState } from 'react';
import Comment from '~/components/challenge/comments/comment';
import { Button } from '~/components/ui/button';
import { toast } from '~/components/ui/use-toast';
import NoComments from '../nocomments';
import { addChallengeComment } from './comment.action';
import { Textarea } from '~/components/ui/textarea';
+import { useInfiniteQuery } from '@tanstack/react-query';
+import { useInView } from 'react-intersection-observer';
+import { getInfiniteComments } from './getCommentRouteData';
+import { CommentSkeleton } from '../comment-skeleton';
interface Props {
- challenge: ChallengeRouteData;
+ challengeId: number;
+ commentCount: number;
}
-const Comments = ({ challenge }: Props) => {
+const Comments = ({ challengeId, commentCount }: Props) => {
const [showComments, setShowComments] = useState(false);
const [text, setText] = useState('');
const [isCommenting, setIsCommenting] = useState(false);
const router = useRouter();
+ const { ref, inView } = useInView();
+
+ const { data, status, hasNextPage, fetchNextPage, isFetchingNextPage } = useInfiniteQuery({
+ queryFn: ({ pageParam = '' }) =>
+ getInfiniteComments({ challengeId, take: 10, lastCursor: pageParam }),
+ queryKey: ['comments'],
+ getNextPageParam: (lastPage) => lastPage.metaData.lastCursor,
+ });
const handleClick = () => {
setShowComments(!showComments);
@@ -35,7 +47,7 @@ const Comments = ({ challenge }: Props) => {
async function createChallengeComment() {
try {
setIsCommenting(true);
- const res = await addChallengeComment(challenge.id, text);
+ const res = await addChallengeComment(challengeId, text);
if (res === 'text_is_empty') {
toast({
title: 'Empty Comment',
@@ -60,6 +72,10 @@ const Comments = ({ challenge }: Props) => {
}
}
+ useEffect(() => {
+ if (inView && hasNextPage) fetchNextPage();
+ }, [hasNextPage, inView, fetchNextPage]);
+
return (
<div className="relative">
<button
@@ -68,7 +84,7 @@ const Comments = ({ challenge }: Props) => {
>
<div className="flex items-center">
<MessageCircle className="h-5 w-5"></MessageCircle>
- &nbsp; Comments ({challenge.comment.length})
+ &nbsp; Comments ({commentCount})
</div>
<ChevronDown
className={clsx('h-4 w-4 duration-300', {
@@ -82,10 +98,23 @@ const Comments = ({ challenge }: Props) => {
'h-0 overflow-y-hidden': !showComments,
})}
>
- {challenge.comment.length === 0 && <NoComments></NoComments>}
- {challenge.comment.map((comment) => (
- <Comment key={comment.id} comment={comment} />
- ))}
+ {(status === 'loading' || isFetchingNextPage) && <CommentSkeleton />}
+ {status === 'success' &&
+ (data?.pages[0]?.data.length === 0 ? (
+ <NoComments></NoComments>
+ ) : (
+ data?.pages.map((page) =>
+ page.data.map((comment, index) =>
+ page.data.length === index + 1 ? (
+ <div ref={ref} key={index}>
+ <Comment key={comment.id} comment={comment} />
+ </div>
+ ) : (
+ <Comment key={comment.id} comment={comment} />
+ ),
+ ),
+ )
+ ))}
</div>
<div className="m-2 mt-0 flex items-end justify-between gap-2 rounded-xl bg-background/90 bg-neutral-100 p-1 pr-2 backdrop-blur-sm dark:border-zinc-700 dark:bg-zinc-700/90">
<Textarea
@@ -93,7 +122,7 @@ const Comments = ({ challenge }: Props) => {
onChange={(e) => {
setText(e.target.value);
}}
- onKeyUp={handleEnterKey}
+ onKeyDown={handleEnterKey}
rows={2}
className="min-h-0 resize-none border-0 focus-visible:ring-0 focus-visible:ring-offset-0"
placeholder="Enter your comment here."