I'm getting data from a Websocketin a Component:
function Data() {
const [price, setPrice] = useState("");
const [date, setDate] = useState("");
const ws = new WebSocket(
"wss://stream.tradingeconomics.com/?client=guest:guest"
);
const subscription = { topic: "subscribe", to: "EURUSD:CUR" };
const initWebsocket = () => {
ws.onopen = () => {
console.log("Connection Established!");
ws.send(JSON.stringify(subscription));
};
ws.onmessage = (event) => {
const response = JSON.parse(event.data);
setPrice(response.price.toFixed(3));
let today = new Date(response.dt * 1);
const options = {
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
};
let date = today.toLocaleDateString("en-EN", options);
setDate(date);
//ws.close();
};
ws.onclose = () => {
console.log("Connection Closed!");
//initWebsocket();
};
ws.onerror = () => {
console.log("WS Error");
};
};
useEffect(() => {
initWebsocket();
// cleanup method which will be called before next execution. in your case unmount.
return () => {
ws.close();
};
}, []);
// useEffect(() => {
// setTimeout(initWebsocket(), 10000);
// }, []);
return (
<div>
Price : {price}
Last Update: {date}
</div>
);
}
export default Data;
Two questions about this:
- with this code, at some point I get the Insuficient Resources Error, but the data still retrieves... I dont know why. 2)if I use the commented useEffect it still getting data from the web socket besides the setTimeout... How can I get data only every 10 seconds?