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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay