admin管理员组文章数量:1148289
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 code is below.
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
</>
)
}```
本文标签: Dynamically updating websocket URL in ReactStack Overflow
版权声明:本文标题:Dynamically updating websocket URL in React - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737260698a1969671.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论