From 3affa30fa620b683bdd55df9da5c48711d07563d Mon Sep 17 00:00:00 2001 From: Mackie Date: Mon, 8 Jun 2026 08:19:46 +0800 Subject: [PATCH] data --- src/hooks/useDashboardData.ts | 25 ++++++++++++++++++++----- src/worker/data.worker.ts | 30 +++++++++++++++++++++++------- 2 files changed, 43 insertions(+), 12 deletions(-) diff --git a/src/hooks/useDashboardData.ts b/src/hooks/useDashboardData.ts index c0d2c9d..bef10ea 100644 --- a/src/hooks/useDashboardData.ts +++ b/src/hooks/useDashboardData.ts @@ -1,23 +1,38 @@ import { useEffect, useState } from 'react'; +// Define the shape of your data +interface MarketUpdate { + symbol: string; + price: string; + id: string; + timestamp: number; +} + export const useDashboardData = () => { - const [data, setData] = useState([]); + // Store the latest price for each symbol in an object + const [latestPrices, setLatestPrices] = useState>({}); useEffect(() => { - // Instantiate the worker const worker = new Worker(new URL('../worker/data.worker.ts', import.meta.url), { type: 'module', }); worker.onmessage = (event) => { if (event.data.type === 'BATCH_UPDATE') { - // Keep only the latest 1000 items to prevent memory bloat - setData((prev) => [...event.data.payload, ...prev].slice(0, 1000)); + setLatestPrices((prev) => { + const newState = { ...prev }; + // Loop through the batch and update only the specific symbol + event.data.payload.forEach((update: MarketUpdate) => { + newState[update.symbol] = update; + }); + return newState; + }); } }; return () => worker.terminate(); }, []); - return data; + // Return the values as an array so you can easily map over them in your UI + return Object.values(latestPrices); }; \ No newline at end of file diff --git a/src/worker/data.worker.ts b/src/worker/data.worker.ts index f10341f..a88b672 100644 --- a/src/worker/data.worker.ts +++ b/src/worker/data.worker.ts @@ -1,12 +1,28 @@ // src/worker/data.worker.ts -const generateUpdate = () => ({ - id: Math.random().toString(36).substring(7), - symbol: "BTC/USD", - price: (Math.random() * 50000).toFixed(2), - timestamp: Date.now(), -}); -// Stream updates every 16ms (target ~60fps) +const symbols = [ + "BTC/USD", + "ETH/USD", + "SOL/USD", + "ADA/USD", + "DOT/USD", + "LINK/USD", + "XRP/USD", + "AVAX/USD" +]; + +const generateUpdate = () => { + // Randomly pick a symbol from the list + const symbol = symbols[Math.floor(Math.random() * symbols.length)]; + + return { + id: Math.random().toString(36).substring(7), + symbol: symbol, + price: (Math.random() * 50000).toFixed(2), + timestamp: Date.now(), + }; +}; + setInterval(() => { const updates = Array.from({ length: 5 }, generateUpdate); self.postMessage({ type: 'BATCH_UPDATE', payload: updates });