Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

chore: fix some analytics display values and UX of activity (#794)

Ameer Al Ashhab92b8332fa36e
diff --git a/apps/web/actions/revalidate-video.ts b/apps/web/actions/revalidate-video.ts
new file mode 100644
index 000000000..0cb592ed1
--- /dev/null
+++ b/apps/web/actions/revalidate-video.ts
@@ -0,0 +1,16 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+
+export async function revalidateVideoPath(videoId: string) {
+ try {
+ revalidatePath(`/s/${videoId}`);
+ return { success: true };
+ } catch (error) {
+ console.error("Failed to revalidate path:", error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : "Unknown error",
+ };
+ }
+}
diff --git a/apps/web/actions/videos/get-analytics.ts b/apps/web/actions/videos/get-analytics.ts
index fe07fa64d..595c21281 100644
--- a/apps/web/actions/videos/get-analytics.ts
+++ b/apps/web/actions/videos/get-analytics.ts
@@ -1,7 +1,6 @@
"use server";
import { dub } from "@/utils/dub";
-import { ClicksCount } from "dub/models/components";
export async function getVideoAnalytics(videoId: string) {
if (!videoId) {
@@ -13,13 +12,13 @@ export async function getVideoAnalytics(videoId: string) {
domain: "cap.link",
key: videoId,
});
- const { clicks: analytics } = response as ClicksCount;
+ const { clicks } = response as { clicks: number };
- if (typeof analytics !== "number" || analytics === null) {
+ if (typeof clicks !== "number" || clicks === null) {
return { count: 0 };
}
- return { count: analytics };
+ return { count: clicks };
} catch (error: any) {
if (error.code === "not_found") {
return { count: 0 };
diff --git a/apps/web/app/(org)/dashboard/caps/Caps.tsx b/apps/web/app/(org)/dashboard/caps/Caps.tsx
index 8179c12b9..f9c83956c 100644
--- a/apps/web/app/(org)/dashboard/caps/Caps.tsx
+++ b/apps/web/app/(org)/dashboard/caps/Caps.tsx
@@ -1,6 +1,5 @@
"use client";
import { deleteVideo } from "@/actions/videos/delete";
-import { useApiClient } from "@/utils/web-api";
import { VideoMetadata } from "@cap/database/types";
import { Button } from "@cap/ui";
import { faFolderPlus } from "@fortawesome/free-solid-svg-icons";
@@ -20,6 +19,7 @@ import Folder from "./components/Folder";
import { faInfoCircle } from "@fortawesome/free-solid-svg-icons";
import type { FolderDataType } from "./components/Folder";
import { useUploadingContext } from "./UploadingContext";
+import { useQuery } from "@tanstack/react-query";
export type VideoData = {
id: string;
@@ -40,7 +40,6 @@ export type VideoData = {
hasPassword: boolean;
}[];
-
export const Caps = ({
data,
count,
@@ -59,7 +58,6 @@ export const Caps = ({
const { refresh } = useRouter();
const params = useSearchParams();
const page = Number(params.get("page")) || 1;
- const [analytics, setAnalytics] = useState<Record<string, number>>({});
const { user } = useDashboardContext();
const limit = 15;
const [openNewFolderDialog, setOpenNewFolderDialog] = useState(false);
@@ -71,40 +69,57 @@ export const Caps = ({
const {
isUploading,
setIsUploading,
- uploadingCapId,
setUploadingCapId,
- uploadingThumbnailUrl,
+ setUploadProgress,
setUploadingThumbnailUrl,
- uploadProgress,
- setUploadProgress
} = useUploadingContext();
const anyCapSelected = selectedCaps.length > 0;
- const apiClient = useApiClient();
+ const { data: analyticsData, isLoading: isLoadingAnalytics } = useQuery({
+ queryKey: ['analytics', data.map(video => video.id)],
+ queryFn: async () => {
+ if (!dubApiKeyEnabled || data.length === 0) {
+ return {};
+ }
- useEffect(() => {
- const fetchAnalytics = async () => {
- if (!dubApiKeyEnabled) return;
+ const analyticsPromises = data.map(async (video) => {
+ try {
+ const response = await fetch(`/api/analytics?videoId=${video.id}`, {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (response.ok) {
+ const responseData = await response.json();
+ return { videoId: video.id, count: responseData.count || 0 };
+ }
+ return { videoId: video.id, count: 0 };
+ } catch (error) {
+ console.warn(`Failed to fetch analytics for video ${video.id}:`, error);
+ return { videoId: video.id, count: 0 };
+ }
+ });
+ const results = await Promise.allSettled(analyticsPromises);
const analyticsData: Record<string, number> = {};
- for (const video of data) {
- const response = await apiClient.video.getAnalytics({
- query: { videoId: video.id },
- fetchOptions: {
- cache: "force-cache",
- },
- });
- if (response.status !== 200) continue;
+ results.forEach((result) => {
+ if (result.status === 'fulfilled' && result.value) {
+ analyticsData[result.value.videoId] = result.value.count;
+ }
+ });
- analyticsData[video.id] = response.body.count || 0;
- }
- setAnalytics(analyticsData);
- };
+ return analyticsData;
+ },
+ enabled: dubApiKeyEnabled && data.length > 0,
+ staleTime: 30000, // 30 seconds
+ refetchOnWindowFocus: false,
+ });
- fetchAnalytics();
- }, [data]);
+ const analytics = analyticsData || {};
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
@@ -161,7 +176,6 @@ export const Caps = ({
};
}, []);
-
const handleCapSelection = (capId: string) => {
setSelectedCaps((prev) => {
const newSelection = prev.includes(capId)
@@ -312,6 +326,7 @@ export const Caps = ({
key={cap.id}
cap={cap}
analytics={analytics[cap.id] || 0}
+ isLoadingAnalytics={isLoadingAnalytics}
onDelete={async () => {
if (selectedCaps.length > 0) {
await deleteSelectedCaps();
diff --git a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx
index 87c2ec337..d2cf689e1 100644
--- a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx
@@ -29,6 +29,7 @@ import { duplicateVideo } from "@/actions/videos/duplicate";
export interface CapCardProps extends PropsWithChildren {
+ isLoadingAnalytics: boolean;
cap: {
id: string;
ownerId: string;
@@ -69,6 +70,7 @@ export interface CapCardProps extends PropsWithChildren {
export const CapCard = ({
cap,
analytics,
+ isLoadingAnalytics,
children,
onDelete,
userId,
@@ -93,11 +95,6 @@ export const CapCard = ({
const router = useRouter();
const { isSubscribed, setUpgradeModalOpen } = useDashboardContext();
- const displayCount =
- analytics === 0
- ? Math.max(cap.totalComments, cap.totalReactions)
- : analytics;
-
const [confirmOpen, setConfirmOpen] = useState(false);
const [removing, setRemoving] = useState(false);
@@ -350,7 +347,7 @@ export const CapCard = ({
<FontAwesomeIcon
className="size-3"
icon={faCopy}
- />f
+ />
<p className="text-sm text-gray-12">Duplicate</p>
</DropdownMenuItem>
<DropdownMenuItem
@@ -459,7 +456,8 @@ export const CapCard = ({
{children}
<CapCardAnalytics
capId={cap.id}
- displayCount={displayCount}
+ displayCount={analytics}
+ isLoadingAnalytics={isLoadingAnalytics}
totalComments={cap.totalComments}
totalReactions={cap.totalReactions}
/>
diff --git a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCardAnalytics.tsx b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCardAnalytics.tsx
index 2e121cabd..523c5298d 100644
--- a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCardAnalytics.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCardAnalytics.tsx
@@ -14,16 +14,17 @@ import {
interface CapCardAnalyticsProps {
capId: string;
displayCount: number;
+ isLoadingAnalytics: boolean;
totalComments: number;
totalReactions: number;
}
export const CapCardAnalytics = Object.assign(
- ({ displayCount, totalComments, totalReactions }: CapCardAnalyticsProps) => (
+ ({ displayCount, isLoadingAnalytics, totalComments, totalReactions }: CapCardAnalyticsProps) => (
<Shell>
<Tooltip content={`${displayCount} unique views`}>
<IconItem icon={faEye}>
- <span className="text-sm text-gray-12">{displayCount ?? "-"}</span>
+ <span className="text-sm text-gray-12">{isLoadingAnalytics ? "..." : displayCount ?? "-"}</span>
</IconItem>
</Tooltip>
<Tooltip content={`${totalComments} comments`}>
diff --git a/apps/web/app/(org)/dashboard/caps/page.tsx b/apps/web/app/(org)/dashboard/caps/page.tsx
index f32652c16..e9e2b536b 100644
--- a/apps/web/app/(org)/dashboard/caps/page.tsx
+++ b/apps/web/app/(org)/dashboard/caps/page.tsx
@@ -16,8 +16,6 @@ export const metadata: Metadata = {
title: "My Caps — Cap",
};
-export const revalidate = 0;
-
export default async function CapsPage({
searchParams,
}: {
diff --git a/apps/web/app/(org)/dashboard/folder/[id]/components/ClientCapCard.tsx b/apps/web/app/(org)/dashboard/folder/[id]/components/ClientCapCard.tsx
index 8ab620c2a..462a6e0b1 100644
--- a/apps/web/app/(org)/dashboard/folder/[id]/components/ClientCapCard.tsx
+++ b/apps/web/app/(org)/dashboard/folder/[id]/components/ClientCapCard.tsx
@@ -8,6 +8,8 @@ import { useState, useRef } from "react";
type ClientCapCardProps = CapCardProps & {
videoId: string;
+ isLoadingAnalytics: boolean;
+ analytics: number;
};
// Interface for drop targets that will be registered for mobile drag and drop
@@ -26,7 +28,7 @@ export function registerDropTarget(
element: HTMLElement,
onDrop: (data: any) => void,
onDragOver?: () => void,
- onDragLeave?: () => void
+ onDragLeave?: () => void,
) {
dropTargets.push({ element, onDrop, onDragOver, onDragLeave });
return () => {
@@ -35,7 +37,7 @@ export function registerDropTarget(
}
export function ClientCapCard(props: ClientCapCardProps) {
- const { videoId, ...rest } = props;
+ const { videoId, isLoadingAnalytics, analytics, ...rest } = props;
const [isDragging, setIsDragging] = useState(false);
const cardRef = useRef<HTMLDivElement>(null);
@@ -103,7 +105,7 @@ export function ClientCapCard(props: ClientCapCardProps) {
onDragEnd={handleDragEnd}
className={isDragging ? "opacity-50" : ""}
>
- <CapCard {...rest} />
+ <CapCard {...rest} analytics={analytics} isLoadingAnalytics={isLoadingAnalytics} />
</div>
);
}
diff --git a/apps/web/app/(org)/dashboard/folder/[id]/components/FolderVideosSection.tsx b/apps/web/app/(org)/dashboard/folder/[id]/components/FolderVideosSection.tsx
index 415ea174b..026d47311 100644
--- a/apps/web/app/(org)/dashboard/folder/[id]/components/FolderVideosSection.tsx
+++ b/apps/web/app/(org)/dashboard/folder/[id]/components/FolderVideosSection.tsx
@@ -3,7 +3,7 @@
import { UploadPlaceholderCard } from "../../../caps/components/UploadPlaceholderCard";
import { ClientCapCard } from "./index";
import { useRouter } from "next/navigation";
-import { useState, useRef, useEffect } from "react";
+import { useState, useRef } from "react";
import { toast } from "sonner";
import { deleteVideo } from "@/actions/videos/delete";
import { SelectedCapsBar } from "../../../caps/components/SelectedCapsBar";
@@ -102,28 +102,49 @@ export default function FolderVideosSection({
});
};
- useEffect(() => {
- const fetchAnalytics = async () => {
- if (!dubApiKeyEnabled) return;
+ const { data: analyticsData, isLoading: isLoadingAnalytics } = useQuery({
+ queryKey: ['analytics', initialVideos.map(video => video.id)],
+ queryFn: async () => {
+ if (!dubApiKeyEnabled || initialVideos.length === 0) {
+ return {};
+ }
+
+ const analyticsPromises = initialVideos.map(async (video) => {
+ try {
+ const response = await fetch(`/api/analytics?videoId=${video.id}`, {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (response.ok) {
+ const responseData = await response.json();
+ return { videoId: video.id, count: responseData.count || 0 };
+ }
+ return { videoId: video.id, count: 0 };
+ } catch (error) {
+ console.warn(`Failed to fetch analytics for video ${video.id}:`, error);
+ return { videoId: video.id, count: 0 };
+ }
+ });
+ const results = await Promise.allSettled(analyticsPromises);
const analyticsData: Record<string, number> = {};
- for (const video of initialVideos) {
- const response = await apiClient.video.getAnalytics({
- query: { videoId: video.id },
- fetchOptions: {
- cache: "force-cache",
- },
- });
- if (response.status !== 200) continue;
+ results.forEach((result) => {
+ if (result.status === 'fulfilled' && result.value) {
+ analyticsData[result.value.videoId] = result.value.count;
+ }
+ });
- analyticsData[video.id] = response.body.count || 0;
- }
- setAnalytics(analyticsData);
- };
+ return analyticsData;
+ },
+ enabled: dubApiKeyEnabled && data.length > 0,
+ staleTime: 30000, // 30 seconds
+ refetchOnWindowFocus: false,
+ });
- fetchAnalytics();
- }, [initialVideos]);
return (
<>
@@ -160,6 +181,7 @@ export default function FolderVideosSection({
videoId={video.id}
cap={video}
analytics={analytics[video.id] || 0}
+ isLoadingAnalytics={isLoadingAnalytics}
isSelected={selectedCaps.includes(video.id)}
anyCapSelected={selectedCaps.length > 0}
isDeleting={isDeleting}
diff --git a/apps/web/app/(org)/dashboard/settings/account/page.tsx b/apps/web/app/(org)/dashboard/settings/account/page.tsx
index ba45ed49d..4645d5f44 100644
--- a/apps/web/app/(org)/dashboard/settings/account/page.tsx
+++ b/apps/web/app/(org)/dashboard/settings/account/page.tsx
@@ -6,8 +6,6 @@ export const metadata: Metadata = {
title: "Settings — Cap",
};
-export const revalidate = 0;
-
export default async function SettingsPage() {
const user = await getCurrentUser();
diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/CustomDomain.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/CustomDomain.tsx
index 693ed8ef8..ed7a52631 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/components/CustomDomain.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/components/CustomDomain.tsx
@@ -1,6 +1,3 @@
-export const revalidate = 0;
-export const fetchCache = "force-no-store";
-
import { checkOrganizationDomain } from "@/actions/organization/check-domain";
import { removeOrganizationDomain } from "@/actions/organization/remove-domain";
import { updateDomain } from "@/actions/organization/update-domain";
diff --git a/apps/web/app/(org)/dashboard/settings/organization/page.tsx b/apps/web/app/(org)/dashboard/settings/organization/page.tsx
index 6bca5b40d..3afd9cd25 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/page.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/page.tsx
@@ -8,8 +8,6 @@ export const metadata: Metadata = {
title: "Organization Settings — Cap",
};
-export const revalidate = 0;
-
export default async function OrganizationPage() {
const user = await getCurrentUser();
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/page.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/page.tsx
index c6cf4a11a..11d7a3dbe 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/page.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/page.tsx
@@ -21,8 +21,6 @@ export const metadata: Metadata = {
title: "Shared Caps — Cap",
};
-export const revalidate = 0;
-
type SpaceData = {
id: string;
name: string;
diff --git a/apps/web/app/(org)/layout.tsx b/apps/web/app/(org)/layout.tsx
index c3801f526..055187cfd 100644
--- a/apps/web/app/(org)/layout.tsx
+++ b/apps/web/app/(org)/layout.tsx
@@ -1,6 +1,8 @@
import { PropsWithChildren } from "react";
import { Intercom } from "../Layout/Intercom";
+export const revalidate = 0;
+
export default function Layout(props: PropsWithChildren) {
return (
<>
diff --git a/apps/web/app/api/analytics/route.ts b/apps/web/app/api/analytics/route.ts
new file mode 100644
index 000000000..18a817e35
--- /dev/null
+++ b/apps/web/app/api/analytics/route.ts
@@ -0,0 +1,22 @@
+import { NextRequest } from "next/server";
+import { getVideoAnalytics } from "@/actions/videos/get-analytics";
+
+export async function GET(request: NextRequest) {
+ const url = new URL(request.url);
+ const videoId = url.searchParams.get("videoId");
+
+ if (!videoId) {
+ return Response.json({ error: "Video ID is required" }, { status: 400 });
+ }
+
+ try {
+ const result = await getVideoAnalytics(videoId);
+ return Response.json({ count: result.count }, { status: 200 });
+ } catch (error) {
+ console.error("Error fetching video analytics:", error);
+ return Response.json(
+ { error: "Failed to fetch analytics" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index 83e1d8cae..6892ecda8 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -1,6 +1,5 @@
"use client";
-import { getVideoAnalytics } from "@/actions/videos/get-analytics";
import { getVideoStatus, VideoStatusResult } from "@/actions/videos/get-status";
import { userSelectProps } from "@cap/database/auth/session";
import { comments as commentsSchema, videos } from "@cap/database/schema";
@@ -120,19 +119,6 @@ const useVideoStatus = (
});
};
-const useVideoAnalytics = (videoId: string, initialCount: number) => {
- return useQuery({
- queryKey: ["videoAnalytics", videoId],
- queryFn: async () => {
- const result = await getVideoAnalytics(videoId);
- return result.count || 0;
- },
- initialData: initialCount,
- staleTime: 30000,
- refetchOnWindowFocus: false,
- });
-};
-
export const Share = ({
data,
user,
diff --git a/apps/web/app/s/[videoId]/_components/Toolbar.tsx b/apps/web/app/s/[videoId]/_components/Toolbar.tsx
index c9d430ac5..27a0bcac7 100644
--- a/apps/web/app/s/[videoId]/_components/Toolbar.tsx
+++ b/apps/web/app/s/[videoId]/_components/Toolbar.tsx
@@ -2,10 +2,10 @@
import { userSelectProps } from "@cap/database/auth/session";
import { videos } from "@cap/database/schema";
import { Button } from "@cap/ui";
-import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { AuthOverlay } from "./AuthOverlay";
+import { revalidateVideoPath } from "@/actions/revalidate-video";
// million-ignore
export const Toolbar = ({
@@ -15,7 +15,6 @@ export const Toolbar = ({
data: typeof videos.$inferSelect;
user: typeof userSelectProps | null;
}) => {
- const { refresh } = useRouter();
const [commentBoxOpen, setCommentBoxOpen] = useState(false);
const [comment, setComment] = useState("");
const [showAuthOverlay, setShowAuthOverlay] = useState(false);
@@ -95,6 +94,8 @@ export const Toolbar = ({
}),
});
+ await revalidateVideoPath(data.id);
+
if (response.status === 429) {
toast.error("Too many requests - please try again later.");
return;
@@ -103,8 +104,6 @@ export const Toolbar = ({
if (!response.ok) {
console.error("Failed to record emoji reaction");
}
-
- refresh();
};
const handleCommentSubmit = async () => {
@@ -137,7 +136,7 @@ export const Toolbar = ({
setComment("");
setCommentBoxOpen(false);
- refresh();
+ await revalidateVideoPath(data.id);
} catch (error) {
console.error("Failed to submit comment:", error);
}
@@ -211,14 +210,12 @@ export const Toolbar = ({
return (
<>
<div
- className={`${
- !commentBoxOpen ? "max-w-[350px]" : "max-w-[500px]"
- } mx-auto`}
+ className={`${!commentBoxOpen ? "max-w-[350px]" : "max-w-[500px]"
+ } mx-auto`}
>
<div
- className={`new-card-style mx-auto transition-all ${
- commentBoxOpen === true && "w-full"
- }`}
+ className={`new-card-style mx-auto transition-all ${commentBoxOpen === true && "w-full"
+ }`}
>
<div className="flex">
<div className="flex-grow p-1">
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity.tsx
index a93bc93fc..86695936a 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Activity.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity.tsx
@@ -1,6 +1,7 @@
"use client";
import { getVideoAnalytics } from "@/actions/videos/get-analytics";
+import { revalidateVideoPath } from "@/actions/revalidate-video";
import { CapCardAnalytics } from "@/app/(org)/dashboard/caps/components/CapCard/CapCardAnalytics";
import { userSelectProps } from "@cap/database/auth/session";
import { comments as commentsSchema } from "@cap/database/schema";
@@ -19,6 +20,8 @@ import {
import { Tooltip } from "react-tooltip";
import { AuthOverlay } from "../AuthOverlay";
+import clsx from "clsx";
+import { useRouter } from "next/navigation";
type CommentType = typeof commentsSchema.$inferSelect & {
authorName?: string | null;
@@ -197,8 +200,7 @@ const Comment: React.FC<{
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.2 }}
- className={`space-y-3 ${level > 0 ? "ml-8 border-l-2 border-gray-100 pl-4" : ""
- }`}
+ className={clsx(`space-y-3`, level > 0 ? "ml-8 border-l-2 border-gray-100 pl-4" : "")}
>
<div className="flex items-start space-x-3">
<Avatar name={comment.authorName} />
@@ -309,9 +311,12 @@ const EmptyState = () => (
export const Activity = Object.assign(
({ user, videoId, isOwnerOrMember = false, ...props }: ActivityProps) => {
- const comments =
+ const initialComments =
props.comments instanceof Promise ? use(props.comments) : props.comments;
+ // Lift comments state up so both Analytics and Comments can share it
+ const [comments, setComments] = useState(initialComments);
+
return (
<Activity.Shell
analytics={
@@ -329,6 +334,7 @@ export const Activity = Object.assign(
{({ setShowAuthOverlay }) => (
<Comments
comments={comments}
+ setComments={setComments}
user={user}
videoId={videoId}
setShowAuthOverlay={setShowAuthOverlay}
@@ -386,10 +392,9 @@ function Analytics(props: {
views: MaybePromise<number>;
comments: CommentType[];
}) {
- const [_views, setViews] = useState(
+ const [views, setViews] = useState(
props.views instanceof Promise ? use(props.views) : props.views
);
- const views = _views === 0 ? props.comments.length : _views;
useEffect(() => {
const fetchAnalytics = async () => {
@@ -403,7 +408,7 @@ function Analytics(props: {
};
fetchAnalytics();
- }, [props.videoId, props.comments.length]);
+ }, [props.videoId]);
const totalComments = useMemo(
() => props.comments.filter((c) => c.type === "text").length,
@@ -427,15 +432,16 @@ function Analytics(props: {
const Comments = Object.assign(
(props: {
- comments: MaybePromise<CommentType[]>;
+ comments: CommentType[]; // Changed from MaybePromise since parent resolves it
+ setComments: React.Dispatch<React.SetStateAction<CommentType[]>>; // Added setComments prop
user: typeof userSelectProps | null;
videoId: string;
onSeek?: (time: number) => void;
setShowAuthOverlay: (v: boolean) => void;
}) => {
- const [comments, setComments] = useState(
- props.comments instanceof Promise ? use(props.comments) : props.comments
- );
+ // Use shared state from parent instead of local state
+ const { comments, setComments } = props;
+ const router = useRouter();
const { user } = props;
const [replyingTo, setReplyingTo] = useState<string | null>(null);
@@ -512,6 +518,8 @@ const Comments = Object.assign(
);
setComments((prev) => [...prev, data]);
+
+ await revalidateVideoPath(props.videoId);
} catch (error) {
console.error("Error posting comment:", error);
setOptimisticComments((prev) =>
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index c8ff64984..f9f7f860a 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -530,6 +530,7 @@ async function AuthorizedContent({
hasPassword: video.password !== null,
};
+
return (
<>
<div className="container flex-1 px-4 py-4 mx-auto">