MCPcopy
hub / github.com/vercel/next.js / useMqtt

Function useMqtt

examples/with-mqtt-js/lib/useMqtt.ts:12–61  ·  view source on GitHub ↗
({
  uri,
  options = {},
  topicHandlers = [{ topic: "", handler: ({ topic, payload, packet }) => {} }],
  onConnectedHandler = (client) => {},
}: useMqttProps)

Source from the content-addressed store, hash-verified

10}
11
12function useMqtt({
13 uri,
14 options = {},
15 topicHandlers = [{ topic: "", handler: ({ topic, payload, packet }) => {} }],
16 onConnectedHandler = (client) => {},
17}: useMqttProps) {
18 const clientRef = useRef<MqttClient | null>(null);
19
20 useEffect(() => {
21 if (clientRef.current) return;
22 if (!topicHandlers || topicHandlers.length === 0) return () => {};
23
24 try {
25 clientRef.current = options
26 ? MQTT.connect(uri, options)
27 : MQTT.connect(uri);
28 } catch (error) {
29 console.error("error", error);
30 }
31
32 const client = clientRef.current;
33 topicHandlers.forEach((th) => {
34 client?.subscribe(th.topic);
35 });
36 client?.on("message", (topic: string, rawPayload: any, packet: any) => {
37 const th = topicHandlers.find((t) => t.topic === topic);
38 let payload;
39 try {
40 payload = JSON.parse(rawPayload);
41 } catch {
42 payload = rawPayload;
43 }
44 if (th) th.handler({ topic, payload, packet });
45 });
46
47 client?.on("connect", () => {
48 if (onConnectedHandler) onConnectedHandler(client);
49 });
50
51 return () => {
52 if (client) {
53 topicHandlers.forEach((th) => {
54 client.unsubscribe(th.topic);
55 });
56 client.end();
57 }
58 };
59 // eslint-disable-next-line react-hooks/exhaustive-deps
60 }, []);
61}
62
63export default useMqtt;

Callers 1

HomeFunction · 0.85

Calls 9

subscribeMethod · 0.80
errorMethod · 0.65
endMethod · 0.65
connectMethod · 0.45
forEachMethod · 0.45
onMethod · 0.45
findMethod · 0.45
parseMethod · 0.45
handlerMethod · 0.45

Tested by

no test coverage detected