Connect, collaborate, and grow with a community of TypeScript developers
Fix comment caching (#318)
bautistaaae98180f05165
diff --git a/src/app/challenge/[id]/getChallengeRouteData.ts b/src/app/challenge/[id]/getChallengeRouteData.tsindex 546bd3d0..fb93ae6d 100644--- a/src/app/challenge/[id]/getChallengeRouteData.ts+++ b/src/app/challenge/[id]/getChallengeRouteData.ts@@ -10,7 +10,7 @@ export const getChallengeRouteData = cache((id: string, session: Session | null)return prisma.challenge.findFirstOrThrow({where: {id: +id,- status: 'ACTIVE'+ status: 'ACTIVE',},include: {user: true,@@ -27,21 +27,6 @@ export const getChallengeRouteData = cache((id: string, session: Session | null)userId: session?.user.id || '',},},- comment: {- where: {- rootType: 'CHALLENGE',- rootChallengeId: +id,- visible: true,- },- include: {- user: true,- },- orderBy: [- {- createdAt: 'desc',- },- ],- },},});});diff --git a/src/app/challenge/[id]/page.tsx b/src/app/challenge/[id]/page.tsxindex 72b71184..f3137ab9 100644--- a/src/app/challenge/[id]/page.tsx+++ b/src/app/challenge/[id]/page.tsx@@ -21,8 +21,7 @@ export default async function Challenges({ params: { id } }: Props) {return (<div className="relative h-full"><Description challenge={challenge}></Description>- {/* BUG: comment length wont update when adding/deleting a comment */}- <Comments rootId={challenge.id} commentCount={challenge.comment.length} type="CHALLENGE" />+ <Comments rootId={challenge.id} type="CHALLENGE" /></div>);}diff --git a/src/components/challenge/comments/comment.action.ts b/src/components/challenge/comments/comment.action.tsindex a40adc3c..f80432e5 100644--- a/src/components/challenge/comments/comment.action.ts+++ b/src/components/challenge/comments/comment.action.ts@@ -72,3 +72,24 @@ export async function deleteComment(comment_id: number) {},});}++export type CommentsByChallengeId = NonNullable<+ Awaited<ReturnType<typeof getCommentsByChallengeId>>+>;+export async function getCommentsByChallengeId(id: number) {+ return await prisma.comment.findMany({+ where: {+ rootType: 'CHALLENGE',+ rootChallengeId: id,+ visible: true,+ },+ include: {+ user: true,+ },+ orderBy: [+ {+ createdAt: 'desc',+ },+ ],+ });+}diff --git a/src/components/challenge/comments/comment.tsx b/src/components/challenge/comments/comment.tsxindex 6422d02c..e93a89ea 100644--- a/src/components/challenge/comments/comment.tsx+++ b/src/components/challenge/comments/comment.tsx@@ -1,24 +1,24 @@'use client';+import { useQueryClient } from '@tanstack/react-query';import clsx from 'clsx';import { Pencil, Reply, Share, Trash2 } from 'lucide-react';import { useSession } from 'next-auth/react';import { useEffect, useRef, useState } from 'react';import { z } from 'zod';-import type { ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';import ReportDialog from '~/components/report';import { Markdown } from '~/components/ui/markdown';import { Tooltip, TooltipContent, TooltipTrigger } from '~/components/ui/tooltip';import { toast } from '~/components/ui/use-toast';import { UserBadge } from '~/components/ui/user-badge';import { getRelativeTime } from '~/utils/relativeTime';-import { CommentDeleteDialog } from './delete';import { CommentInput } from './comment-input';-import { updateComment } from './comment.action';-import { useQueryClient } from '@tanstack/react-query';+import { updateComment, type CommentsByChallengeId } from './comment.action';+import { CommentDeleteDialog } from './delete';interface CommentProps {- comment: ChallengeRouteData['comment'][number];+ comment: CommentsByChallengeId[number];+ queryKey?: (string | number)[];readonly?: boolean;}@@ -43,7 +43,7 @@ const commentReportSchema = zexport type CommentReportSchemaType = z.infer<typeof commentReportSchema>;-export const Comment = ({ comment, readonly = false }: CommentProps) => {+export const Comment = ({ comment, queryKey, readonly = false }: CommentProps) => {const queryClient = useQueryClient();const [text, setText] = useState(comment.text);const [isEditing, setIsEditing] = useState(false);@@ -86,7 +86,7 @@ export const Comment = ({ comment, readonly = false }: CommentProps) => {description: <p>You need to be signed in to post a comment.</p>,});}- queryClient.invalidateQueries([`challenge-${comment.rootChallengeId}-comments`]);+ queryClient.invalidateQueries(queryKey);} catch (e) {toast({title: 'Unauthorized',@@ -149,7 +149,7 @@ export const Comment = ({ comment, readonly = false }: CommentProps) => {)}{/* TODO: make dis work */}{isAuthor ? (- <CommentDeleteDialog comment={comment} asChild>+ <CommentDeleteDialog comment={comment} queryKey={queryKey} asChild><button className="flex cursor-pointer items-center gap-1 text-neutral-500 duration-200 hover:text-neutral-400 dark:text-neutral-400 dark:hover:text-neutral-300"><Trash2 className="h-3 w-3" /><div className="hidden text-[0.8rem] sm:block">Delete</div>diff --git a/src/components/challenge/comments/delete/index.tsx b/src/components/challenge/comments/delete/index.tsxindex 6b7da3d5..0405f525 100644--- a/src/components/challenge/comments/delete/index.tsx+++ b/src/components/challenge/comments/delete/index.tsx@@ -1,7 +1,6 @@import { type DialogTriggerProps } from '@radix-ui/react-dialog';import { useQueryClient } from '@tanstack/react-query';import { useState } from 'react';-import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';import { TypographyP } from '~/components//ui/paragraph';import { Button } from '~/components/ui/button';import { Dialog, DialogContent, DialogTrigger } from '~/components/ui/dialog';@@ -9,13 +8,19 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '~/components/ui/tooltipimport { TypographyLarge } from '~/components/ui/typography/large';import { toast } from '~/components/ui/use-toast';import { getRelativeTime } from '~/utils/relativeTime';-import { deleteComment } from '../comment.action';+import { deleteComment, type CommentsByChallengeId } from '../comment.action';interface CommentDeleteDialogProps extends DialogTriggerProps {- comment: ChallengeRouteData['comment'][number];+ comment: CommentsByChallengeId[number];+ queryKey?: (string | number)[];}-export const CommentDeleteDialog = ({ children, comment, ...props }: CommentDeleteDialogProps) => {+export const CommentDeleteDialog = ({+ children,+ comment,+ queryKey,+ ...props+}: CommentDeleteDialogProps) => {const [isOpen, setIsOpen] = useState(false);const queryClient = useQueryClient();@@ -36,7 +41,7 @@ export const CommentDeleteDialog = ({ children, comment, ...props }: CommentDeledescription: 'An error occurred while trying to delete the comment.',});} finally {- queryClient.invalidateQueries([`challenge-${comment.rootChallengeId}-comments`]);+ queryClient.invalidateQueries(queryKey);setIsOpen(!isOpen);}}diff --git a/src/components/challenge/comments/getCommentRouteData.ts b/src/components/challenge/comments/getCommentRouteData.tsindex 019835b5..690980e4 100644--- a/src/components/challenge/comments/getCommentRouteData.ts+++ b/src/components/challenge/comments/getCommentRouteData.ts@@ -41,6 +41,7 @@ export async function getPaginatedComments({return {totalPages,+ totalComments,hasMore: page < totalPages,comments,};diff --git a/src/components/challenge/comments/index.tsx b/src/components/challenge/comments/index.tsxindex 639d4d70..0b5ce236 100644--- a/src/components/challenge/comments/index.tsx+++ b/src/components/challenge/comments/index.tsx@@ -17,11 +17,10 @@ import NoComments from './nocomments';interface Props {rootId: number;- commentCount: number;type: CommentRoot;}-export const Comments = ({ rootId, commentCount, type }: Props) => {+export const Comments = ({ rootId, type }: Props) => {const [showComments, setShowComments] = useState(false);const [text, setText] = useState('');const commentContainerRef = useRef<HTMLDivElement>(null);@@ -30,11 +29,10 @@ export const Comments = ({ rootId, commentCount, type }: Props) => {const [page, setPage] = useState(1);- const queryKey =- type === 'CHALLENGE' ? `challenge-${rootId}-comments` : `solution-${rootId}-comments`;+ const queryKey = [`${type.toLowerCase()}-${rootId}-comments`, page];const { status, data } = useQuery({- queryKey: [queryKey, page],+ queryKey,queryFn: () => getPaginatedComments({ rootId, page, rootType: type }),keepPreviousData: true,staleTime: 5000,@@ -66,7 +64,7 @@ export const Comments = ({ rootId, commentCount, type }: Props) => {});}setText('');- queryClient.invalidateQueries([queryKey, page]);+ queryClient.invalidateQueries(queryKey);} catch (e) {toast({title: 'Unauthorized',@@ -102,7 +100,8 @@ export const Comments = ({ rootId, commentCount, type }: Props) => {><div className="flex items-center gap-2"><MessageCircle className="h-5 w-5" />- Comments ({commentCount})+ Comments+ {data?.totalComments != null && <span>({data?.totalComments})</span>}</div><ChevronDownclassName={clsx('h-4 w-4 duration-300', {@@ -136,7 +135,9 @@ export const Comments = ({ rootId, commentCount, type }: Props) => {(data.comments.length === 0 ? (<NoComments />) : (- data?.comments?.map((comment) => <Comment key={comment.id} comment={comment} />)+ data?.comments?.map((comment) => (+ <Comment key={comment.id} comment={comment} queryKey={queryKey} />+ ))))}</div>{(data?.totalPages ?? 0) > 1 && (diff --git a/src/components/challenge/solutions/solution-detail.tsx b/src/components/challenge/solutions/solution-detail.tsxindex 55266ab3..f353c978 100644--- a/src/components/challenge/solutions/solution-detail.tsx+++ b/src/components/challenge/solutions/solution-detail.tsx@@ -91,11 +91,7 @@ export function SolutionDetails({ solution }: Props) {<Markdown>{solution.description || ''}</Markdown></div></div>- <Comments- rootId={solution.id as number}- commentCount={solution.jimComments.length}- type="SOLUTION"- />+ <Comments rootId={solution.id as number} type="SOLUTION" /></div>);}diff --git a/src/components/user/dashboard/user-header.tsx b/src/components/user/dashboard/user-header.tsxindex 45247b67..fe9022d1 100644--- a/src/components/user/dashboard/user-header.tsx+++ b/src/components/user/dashboard/user-header.tsx@@ -1,7 +1,6 @@'use client';import Text from '~/components/ui/typography/typography';-import { UserData } from './index';import { type User } from '@prisma/client';import ReportDialog from '~/components/report';import { ActionMenu } from '~/components/ui/action-menu';diff --git a/tsconfig.json b/tsconfig.jsonindex f323b5f8..3319f37c 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -6,6 +6,7 @@"checkJs": false,"skipLibCheck": true,"strict": true,+ "verbatimModuleSyntax": true,"forceConsistentCasingInFileNames": true,"noEmit": true,"esModuleInterop": true,