Skip to content

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

chore: fixed cache on solutions related routes and removed redundant queries (#1094)

Ayush Kumar Yadav6029e87ff995
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/delete/index.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/delete/index.tsx
index 9a3ba32f..158c52a7 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/delete/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/delete/index.tsx
@@ -3,21 +3,25 @@ import { useState } from 'react';
import { Dialog, DialogContent, DialogTrigger } from '@repo/ui/components/dialog';
import { TypographyLarge } from '@repo/ui/components/typography/large';
import type { ChallengeSolution } from '~/app/[locale]/challenge/[slug]/solutions/[solutionId]/page';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';
-import { getRelativeTime } from '~/utils/relativeTime';
import { Button } from '@repo/ui/components/button';
import { TypographyP } from '@repo/ui/components/paragraph';
-import { Markdown } from '@repo/ui/components/markdown';
-import { Label } from '@repo/ui/components/label';
import { deleteSolution } from '../_actions';
import { toast } from '@repo/ui/components/use-toast';
import { useRouter } from 'next/navigation';
+import { useQueryClient } from '@tanstack/react-query';
interface SolutionDeleteDialogProps extends DialogTriggerProps {
solution: ChallengeSolution;
+ slug: string[] | string | undefined;
}
-export function SolutionDeleteDialog({ children, solution, ...props }: SolutionDeleteDialogProps) {
+export function SolutionDeleteDialog({
+ children,
+ slug,
+ solution,
+ ...props
+}: SolutionDeleteDialogProps) {
+ const queryClient = useQueryClient();
const [isOpen, setIsOpen] = useState(false);
const router = useRouter();
@@ -29,6 +33,13 @@ export function SolutionDeleteDialog({ children, solution, ...props }: SolutionD
variant: 'success',
description: 'The solution was successfully deleted.',
});
+ // invalidate cache on deleting a solution successfully
+ queryClient.invalidateQueries({
+ queryKey: ['challenge-solutions', slug],
+ });
+ queryClient.refetchQueries({
+ queryKey: ['challenge-solutions', slug],
+ });
router.back();
} catch (e) {
toast({
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/index.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/index.tsx
index 7d2dd37e..a63c4f8e 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/index.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/index.tsx
@@ -7,7 +7,7 @@ import { useRef, useState } from 'react';
import { SolutionEditor } from './solution-editor';
import { NoSolutions } from './nosolutions';
import { SubmitSolution } from './submit-solution';
-import { type ChallengeSolution, getPaginatedSolutions } from '../getSolutionRouteData';
+import { type PaginatedSolution, getPaginatedSolutions } from '../getSolutionRouteData';
import { getRelativeTime } from '~/utils/relativeTime';
import { Badge } from '@repo/ui/components/badge';
import { UserBadge } from '@repo/ui/components/user-badge';
@@ -18,13 +18,10 @@ import { SolutionsSkeleton } from './solution-skeleton';
import { SortSelect } from '../../../_components/sort-select';
interface Props {
- challenge: ChallengeSolution;
slug: string;
}
-type View = 'details' | 'editor' | 'list';
-
-const sortKeys = [
+export const SORT_KEYS = [
{
label: 'Newest Solutions',
value: 'newest',
@@ -45,28 +42,30 @@ const sortKeys = [
},
] as const;
-export function Solutions({ challenge, slug }: Props) {
+type View = 'details' | 'editor' | 'list';
+
+export function Solutions({ slug }: Props) {
const [view, setView] = useState<View>('list');
const commentContainerRef = useRef<HTMLDivElement>(null);
- const [sortKey, setSortKey] = useState<(typeof sortKeys)[number]>(sortKeys[0]);
+ const [sortKey, setSortKey] = useState<(typeof SORT_KEYS)[number]>(SORT_KEYS[0]);
const [page, setPage] = useState(1);
- const queryKey = ['paginated-solutions', slug, page, sortKey.key, sortKey.order];
+ const queryKey = ['challenge-solutions', slug, page, sortKey.key, sortKey.order];
const session = useSession();
const handleChangePage = (page: number) => {
setPage(page);
commentContainerRef.current?.scroll({
- top: 128,
+ top: 0,
behavior: 'smooth',
});
};
const handleValueChange = (value: string) => {
- setSortKey(sortKeys.find((sk) => sk.value === value) ?? sortKeys[0]);
+ setSortKey(SORT_KEYS.find((sk) => sk.value === value) ?? SORT_KEYS[0]);
setPage(1);
};
- const { status, data } = useQuery({
+ const { status, data: pageData } = useQuery({
queryKey,
queryFn: () =>
getPaginatedSolutions({ slug, page, sortKey: sortKey.key, sortOrder: sortKey.order }),
@@ -75,17 +74,21 @@ export function Solutions({ challenge, slug }: Props) {
refetchOnWindowFocus: false,
});
- const loggedInUserHasSolution = challenge.submission.length;
+ const loggedInUserHasSolution = pageData?.submission?.length ?? 0;
return (
<div className="flex h-full flex-col">
- {view === 'editor' && (
- <SolutionEditor challenge={challenge} dismiss={() => setView('list')} />
- )}
+ {view === 'editor' && pageData?.id ? (
+ <SolutionEditor
+ challengeId={pageData.id}
+ code={pageData?.submission?.[0]?.code}
+ dismiss={() => setView('list')}
+ />
+ ) : null}
{view === 'list' && (
<>
- {data?.solutions.length !== 0 ? (
+ {pageData?.sharedSolution?.length !== 0 ? (
<>
{status === 'loading' && <SolutionsSkeleton />}
{status === 'success' && (
@@ -98,26 +101,26 @@ export function Solutions({ challenge, slug }: Props) {
ref={commentContainerRef}
>
<div>
- {(data?.solutions.length ?? 0) > 0 && (
+ {(pageData?.sharedSolution?.length ?? 0) > 0 && (
<SortSelect
currentSortKey={sortKey}
- totalSortKeys={sortKeys}
+ totalSortKeys={SORT_KEYS}
onValueChange={handleValueChange}
/>
)}
</div>
<div className="flex-1">
{status === 'success' &&
- data?.solutions.map((solution) => (
+ pageData?.sharedSolution?.map((solution) => (
<SolutionRow key={solution.id} solution={solution} />
))}
</div>
- {(data?.totalPages ?? 0) > 1 && (
+ {(pageData?.totalPages ?? 0) > 1 && (
<div className="mb-2 flex justify-center">
<Pagination
currentPage={page}
onClick={handleChangePage}
- totalPages={data?.totalPages ?? 0}
+ totalPages={pageData?.totalPages ?? 0}
/>
</div>
)}
@@ -136,7 +139,11 @@ export function Solutions({ challenge, slug }: Props) {
);
}
-function SolutionRow({ solution }: { solution: ChallengeSolution['sharedSolution'][0] }) {
+function SolutionRow({
+ solution,
+}: {
+ solution: NonNullable<PaginatedSolution['sharedSolution']>[number];
+}) {
const { slug } = useParams();
return (
<Link
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-detail.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-detail.tsx
index 62a57786..d3a7d1ee 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-detail.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-detail.tsx
@@ -152,7 +152,7 @@ export function SolutionDetails({ solution }: Props) {
<p>Edit</p>
</TooltipContent>
</Tooltip>
- <SolutionDeleteDialog solution={solution}>
+ <SolutionDeleteDialog solution={solution} slug={slug}>
<Tooltip>
<TooltipTrigger asChild>
<Button variant="secondary" size="xs">
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-editor.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-editor.tsx
index dc0e5c5f..5ad68e5d 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-editor.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/_components/solution-editor.tsx
@@ -10,7 +10,6 @@ import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { RichMarkdownEditor } from '~/components/rich-markdown-editor';
import { createNoProfanitySchemaWithValidate } from '~/utils/antiProfanityZod';
-import type { ChallengeSolution } from '../getSolutionRouteData';
import { postSolution } from './_actions';
import { useQueryClient } from '@tanstack/react-query';
@@ -40,11 +39,12 @@ const formSchema = z.object({
export type FormSchema = z.infer<typeof formSchema>;
interface Props {
- challenge: ChallengeSolution;
+ challengeId: number;
+ code?: string;
dismiss: () => void;
}
-export function SolutionEditor({ dismiss, challenge }: Props) {
+export function SolutionEditor({ dismiss, challengeId, code }: Props) {
const { slug } = useParams();
const queryClient = useQueryClient();
const session = useSession();
@@ -52,7 +52,7 @@ export function SolutionEditor({ dismiss, challenge }: Props) {
resolver: zodResolver(formSchema),
defaultValues: {
title: `${session.data?.user.name}'s Solution`,
- content: getDefaultMarkdown(challenge.submission[0]?.code ?? ''),
+ content: getDefaultMarkdown(code ?? ''),
},
});
const { toast } = useToast();
@@ -60,7 +60,7 @@ export function SolutionEditor({ dismiss, challenge }: Props) {
const onSubmit = async (data: FormSchema) => {
try {
await postSolution({
- challengeId: challenge.id,
+ challengeId,
description: data.content ?? '',
slug: slug as string,
title: data.title ?? `${session.data?.user.name}'s Solution`,
@@ -71,14 +71,20 @@ export function SolutionEditor({ dismiss, challenge }: Props) {
variant: 'success',
title: 'Your solution has been posted!',
});
+
+ // invalidate cache on adding a solution successfully
+ queryClient.invalidateQueries({
+ queryKey: [`challenge-solutions`, slug],
+ });
+ queryClient.refetchQueries({
+ queryKey: ['challenge-solutions', slug],
+ });
} catch (error) {
toast({
variant: 'destructive',
title: 'Uh oh! Something went wrong. Please try again.',
});
} finally {
- // Todo: It just works
- queryClient.refetchQueries([`paginated-solutions`, slug]);
dismiss();
}
};
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/solutions/getSolutionRouteData.ts b/apps/web/src/app/[locale]/challenge/[slug]/solutions/getSolutionRouteData.ts
index 0cd5ccc9..138600ef 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/solutions/getSolutionRouteData.ts
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/getSolutionRouteData.ts
@@ -1,17 +1,32 @@
'use server';
-import { cache } from 'react';
import { prisma } from '@repo/db';
-import { type Session } from '@repo/auth/server';
+import { getServerAuthSession, type Session } from '@repo/auth/server';
import type { SortKey, SortOrder } from '~/utils/sorting';
import { orderBy } from '~/utils/sorting';
const PAGESIZE = 10;
-export type ChallengeSolution = NonNullable<Awaited<ReturnType<typeof getSolutionsRouteData>>>;
-export const getSolutionsRouteData = cache(async (slug: string, session: Session | null) => {
+export type PaginatedSolution = NonNullable<Awaited<ReturnType<typeof getPaginatedSolutions>>>;
+export async function getPaginatedSolutions({
+ slug,
+ page,
+ sortKey = 'createdAt',
+ sortOrder = 'desc',
+}: {
+ slug: string;
+ page: number;
+ sortKey?: SortKey;
+ sortOrder?: SortOrder;
+}) {
+ const session = await getServerAuthSession();
const data = await prisma.challenge.findFirst({
where: { slug },
select: {
+ _count: {
+ select: {
+ sharedSolution: true,
+ },
+ },
id: true,
submission: {
where: {
@@ -26,13 +41,13 @@ export const getSolutionsRouteData = cache(async (slug: string, session: Session
take: 1,
},
sharedSolution: {
+ skip: (page - 1) * PAGESIZE,
+ take: PAGESIZE,
orderBy: [
{
- isPinned: 'desc',
- },
- {
- createdAt: 'desc',
+ isPinned: 'desc' as SortOrder,
},
+ orderBy(sortKey, sortOrder),
],
include: {
user: {
@@ -48,55 +63,13 @@ export const getSolutionsRouteData = cache(async (slug: string, session: Session
},
});
- return data;
-});
-
-export async function getPaginatedSolutions({
- slug,
- page,
- sortKey = 'createdAt',
- sortOrder = 'desc',
-}: {
- slug: string;
- page: number;
- sortKey?: SortKey;
- sortOrder?: SortOrder;
-}) {
- const challenge = await prisma.challenge.findFirst({
- where: { slug },
- });
-
- const solutions = await prisma.sharedSolution.findMany({
- where: { challengeId: challenge?.id },
- skip: (page - 1) * PAGESIZE,
- take: PAGESIZE,
- orderBy: [
- {
- isPinned: 'desc' as SortOrder,
- },
- orderBy(sortKey, sortOrder),
- ],
- include: {
- user: {
- select: {
- name: true,
- },
- },
- _count: {
- select: { vote: true, solutionComment: true },
- },
- },
- });
-
- const totalSolutions = await prisma.sharedSolution.count({
- where: { challengeId: challenge?.id },
- });
+ const totalSolutions = data?._count?.sharedSolution || 0;
const totalPages = Math.ceil(totalSolutions / PAGESIZE);
return {
+ ...data,
totalPages,
hasMore: page < totalPages,
- solutions,
};
}
diff --git a/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx b/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx
index 3929cfcd..b003d585 100644
--- a/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[slug]/solutions/page.tsx
@@ -1,11 +1,6 @@
-import { getServerAuthSession } from '@repo/auth/server';
-import { notFound } from 'next/navigation';
import { buildMetaForDefault } from '~/app/metadata';
-import { withUnstableCache } from '~/utils/withUnstableCache';
import { getChallengeRouteData } from '../getChallengeRouteData';
import { Solutions } from './_components';
-import { getSolutionsRouteData } from './getSolutionRouteData';
-import { createCacheKeyForSolutions } from './_components/_actions';
interface Props {
params: {
@@ -22,17 +17,5 @@ export async function generateMetadata({ params: { slug } }: Props) {
}
export default async function SolutionPage({ params: { slug } }: Props) {
- const session = await getServerAuthSession();
- const solutions = await withUnstableCache({
- fn: getSolutionsRouteData,
- args: [slug, session],
- keys: ['challenge-solutions'],
- tags: [createCacheKeyForSolutions(slug)],
- });
-
- if (!solutions) {
- return notFound();
- }
-
- return <Solutions challenge={solutions} slug={slug} />;
+ return <Solutions slug={slug} />;
}