3

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

9 Comments

this does not work...
I updated the answer. you can have a look
this gets the data, but do not obey the setTime interval... it still gets the data every time. another thing is tha I get the Insuficient Resources error after a while... do you know why?
did you check the code on sandbox? I dont get insufficient error there. I kept open for 5 mins though. trick was to put ```` const ws = new WebSocket( "wss://stream.tradingeconomics.com/?client=guest:guest" );```` inside useEffect. with code above, you dont need setInterval. because it keeps the connection live whenever price changes. The reason why you get insufficient resources, you create the socket in the component body and run it inside useEffect. problem is everytime price gets updated, you run the same code again. that means creating a new socket on each render
yes, Ive checked with the code without set interval. But the error still happens after a while. On sandbox is ok, no error.... maybe is something with Chrome?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.