DEV Community

Barry Martin
Barry Martin

Posted on

Dynamically updating websocket URL with useEffect

I have a react app that uses web sockets. When the page loads I need to run an async function that retrieves the MDNS name of the unit. I then am trying to use this MDNS name as part of the web socket URL connection. I'm not an expert so I'm wondering if all the useEffects run concurrently or one after the other. Any suggestions as to how to solve this would be appreciated. The getMDNS and getUserNames work correctly, I'm just getting the error in the browser log window:

index-EUpgzpwz.js:40 SyntaxError: Failed to construct 'WebSocket': The URL 'ws://[object Object].local/ws' is invalid.

The code is below. Any help would be appreciated.


import { useEffect, useState } from "react";
export default function DataTables() {
  const [tc1user, setTc1User] = useState<any>("TC1 User Name");
  const [tc2user, setTc2User] = useState<any>("TC2 User Name");
  const [tc1, setTc1] = useState<number>(0);
  const [tc2, setTc2] = useState<number>(0);
  const [mdns, setMdns] = useState("");

  useEffect(() => {
    const getMdns = async () => {
      // setIsLoading(true);
      try {
        const webResult = await fetch("/api/get-mdns");
        const myText = await webResult.text();
        const mdnsjson = JSON.parse(myText);
        setMdns(mdnsjson.mdns);
        // console.log(mdnsjson.mdns);
      } catch (error) {
        console.log("Error fetching mdns", error);
      } finally {
        // setIsLoading(false);
      }
    }
    getMdns();
  }, []);

  useEffect(() => {
    const getUserNames = async () => {
      try {
        const webResult = await fetch("/api/get-user");
        const myText = await webResult.text();
        const userjson = JSON.parse(myText);
        setTc1User(userjson[0].role);
        setTc2User(userjson[1].role);
      } catch (error) {
        console.log("Error fetching data", error);
      } finally {
      }
    }
    getUserNames();
  }, []);

  useEffect(() => {
    let webmdns = mdns;
    webmdns = "ws://" + webmdns + ".local/ws"
    const ws = new WebSocket(webmdns); // Connect to websocket using mdns name currently in use

    ws.onopen = () => {
      console.log('WebSocket connected');
    };
    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      setTc1(data.TC1);
      setTc2(data.TC2);
    };
    ws.onerror = (error) => {
      console.error('WebSocket error:', error);
    };
    return () => {
      ws.close();
      console.log('WebSocket disconnected');
    };
  }, []);

  return (
    <>
    // Do stuff here
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)