"use client"; import React, { useEffect, useState } from "react"; import Image from "next/image"; import Link from "next/link"; import { ArrowUp, ArrowDown, Bell } from "lucide-react"; import CreateAlertModal from "./CreateAlertModal"; import WatchlistButton from "@/components/WatchlistButton"; import { formatCurrency, formatNumber } from "@/lib/utils"; import { removeFromWatchlist } from "@/lib/actions/watchlist.actions"; interface WatchlistTableProps { data: any[]; userId: string; onRefresh?: () => void; } export default function WatchlistTable({ data, userId, onRefresh }: WatchlistTableProps) { const [stocks, setStocks] = useState(data); useEffect(() => { // Initial set if prop changes setStocks(data); }, [data]); useEffect(() => { if (!stocks || stocks.length === 0) return; // Poll for price updates every 15 seconds const interval = setInterval(async () => { try { const symbols = stocks.map(s => s.symbol); if (symbols.length === 0) return; // Dynamic import to avoid server-action issues if directly imported in client component sometimes const { getWatchlistData } = await import('@/lib/actions/finnhub.actions'); const updatedData = await getWatchlistData(symbols); if (updatedData && updatedData.length > 0) { setStocks(current => { const map = new Map(updatedData.map(item => [item.symbol, item])); return current.map(existing => { const fresh = map.get(existing.symbol); if (fresh) { return { ...existing, price: fresh.price, change: fresh.change, changePercent: fresh.changePercent, }; } return existing; }); }); } } catch (err) { console.error("Failed to poll watchlist prices", err); } }, 5000); return () => clearInterval(interval); }, [stocks]); // Re-create interval if list size changes if (!stocks || stocks.length === 0) { return (

Your watchlist is empty

Add stocks to track their performance and set alerts.

); } return (
{stocks.map((stock: any) => { const isPositive = stock.change >= 0; return ( ); })}
Company Symbol Price Change Market Cap Actions
{stock.logo ? (
{stock.symbol}
) : (
{stock.symbol[0]}
)}
{stock.name}
{stock.symbol} {formatCurrency(stock.price)}
{isPositive ? : } {Math.abs(stock.changePercent).toFixed(2)}%
{formatNumber(stock.marketCap)}
{ if (!added) { await removeFromWatchlist(userId, sym); // Update local list faster than full page refresh if you want setStocks((curr: any[]) => curr.filter((s: any) => s.symbol !== sym)); if (onRefresh) onRefresh(); } }} />
); }