-
Notifications
You must be signed in to change notification settings - Fork 0
/
LiveTicker.tsx
98 lines (83 loc) · 2.72 KB
/
LiveTicker.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import * as React from 'react';
import styled from 'styled-components';
import { StockPrice } from '../../components';
import { tickerSymbols } from '../../data/symbols';
const enum Classes {
TickerContainer = 'ticker-container',
StockContainer = 'ticker-stock-container',
StockSymbol = 'ticker-stock-symbol',
StockCurrentPrice = 'ticker-stock-currentp-price',
}
export const LiveTicker = () => {
const ws = React.useRef<WebSocket | null>(null);
const initialStocks = tickerSymbols.map((symbol) => ({
symbol,
price: 0,
timestamp: Date.now(),
}));
// Initially populate liveStock with initial data, then update with socket response
const [stocks, setStocks] = React.useState(initialStocks);
React.useEffect(() => {
const url = `wss://ws.finnhub.io?token=${process.env.FINNHUB_API_TOKEN}`;
ws.current = new WebSocket(url);
// Subscribe to some stocks
ws.current.onopen = () => {
console.log('websocket is open, subscribing to trades:');
tickerSymbols.forEach((symbol) => {
ws.current.send(JSON.stringify({ type: 'subscribe', symbol }));
});
};
ws.current.onclose = () => console.log('Connection closed');
// Listen for messages
ws.current.onmessage = (e: MessageEvent) => {
// console.log('receiving message from servvver');
const { data } = JSON.parse(e.data);
const { s: symbol, p: price, t: timestamp } = data[0];
setStocks((prevState) => {
const indexToUpdate = prevState.findIndex((s) => s.symbol === symbol);
const newState = [...prevState];
newState[indexToUpdate] = { symbol, price, timestamp };
return newState;
});
};
return () => {
console.log('unsubscribing to web socket');
// Unsubscribe to the trades
tickerSymbols.forEach((symbol) => {
ws.current.send(JSON.stringify({ type: 'unsubscribe', symbol }));
});
};
}, []);
const renderTicker = () => {
return (
<div className={Classes.TickerContainer}>
{stocks.map((s) => {
return (
<div key={s.symbol} className={Classes.StockContainer}>
<span className={Classes.StockSymbol}>{s.symbol}</span>
<StockPrice value={s.price} />
</div>
);
})}
</div>
);
};
return <StyledStaticTicker>{renderTicker()}</StyledStaticTicker>;
};
const StyledStaticTicker = styled.div`
height: 80px;
background: lightgrey;
.${Classes.TickerContainer} {
display: flex;
flex-direction: column;
}
.${Classes.StockContainer} {
border: 2px grey solid;
border-radius: 4px;
min-width: 100px;
max-width: 100px;
display: flex;
align-items: center;
justify-content: space-between;
}
`;