Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching Data from WebSocket React

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:

  1. 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?
like image 454
miouri Avatar asked Jun 05 '26 07:06

miouri


1 Answers

you can use setInterval to run a code block within defined period.

setInterval(()=>{your function}, 10000)

This was just answer of your last question. If you want to run a code periodically, setInterval is your guy.

I edited your code a bit at code sandbox:

import "./styles.css";
import { useState, useEffect } from "react";

export default function App() {
  const [price, setPrice] = useState("");
  const [date, setDate] = useState("");

  const subscription = { topic: "subscribe", to: "EURUSD:CUR" };

  useEffect(() => {
    const ws = new WebSocket(
      "wss://stream.tradingeconomics.com/?client=guest:guest"
    );

    ws.onopen = () => {
      console.log("Connection Established!");
      ws.send(JSON.stringify(subscription));
    };
    ws.onmessage = (event) => {
      const response = JSON.parse(event.data);
      console.log(response);

      if (response.topic === "EURUSD") {
        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");
    };

    return () => {
      ws.close();
    };
  }, []);

  // useEffect(() => {
  //   setTimeout(initWebsocket(), 10000);
  // }, []);

  return (
    <div>
      <p>Price : {price}</p>
      <p>Last Update: {date}</p>
    </div>
  );
}

what I did, basically I put entire socket connection inside the useEffect and also put an if condition for the response.

https://codesandbox.io/embed/dark-fog-msg3v?fontsize=14&hidenavigation=1&theme=dark

like image 60
Deniz Karadağ Avatar answered Jun 07 '26 23:06

Deniz Karadağ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!