Files
StevenandGitHub 4466ba436b chore(examples): use default prettier for examples/templates (#60530)
## Description
This PR ensures that the default prettier config is used for examples
and templates.

This config is compatible with `prettier@3` as well (upgrading prettier
is bigger change that can be a future PR).

## Changes
- Updated `.prettierrc.json` in root with `"trailingComma": "es5"` (will
be needed upgrading to prettier@3)
- Added `examples/.prettierrc.json` with default config (this will
change every example)
- Added `packages/create-next-app/templates/.prettierrc.json` with
default config (this will change every template)

## Related

- Fixes #54402
- Closes #54409
2024-01-11 16:01:44 -07:00

64 lines
1.6 KiB
TypeScript

import type { MqttClient, IClientOptions } from "mqtt";
import MQTT from "mqtt";
import { useEffect, useRef } from "react";
interface useMqttProps {
uri: string;
options?: IClientOptions;
topicHandlers?: { topic: string; handler: (payload: any) => void }[];
onConnectedHandler?: (client: MqttClient) => void;
}
function useMqtt({
uri,
options = {},
topicHandlers = [{ topic: "", handler: ({ topic, payload, packet }) => {} }],
onConnectedHandler = (client) => {},
}: useMqttProps) {
const clientRef = useRef<MqttClient | null>(null);
useEffect(() => {
if (clientRef.current) return;
if (!topicHandlers || topicHandlers.length === 0) return () => {};
try {
clientRef.current = options
? MQTT.connect(uri, options)
: MQTT.connect(uri);
} catch (error) {
console.error("error", error);
}
const client = clientRef.current;
topicHandlers.forEach((th) => {
client?.subscribe(th.topic);
});
client?.on("message", (topic: string, rawPayload: any, packet: any) => {
const th = topicHandlers.find((t) => t.topic === topic);
let payload;
try {
payload = JSON.parse(rawPayload);
} catch {
payload = rawPayload;
}
if (th) th.handler({ topic, payload, packet });
});
client?.on("connect", () => {
if (onConnectedHandler) onConnectedHandler(client);
});
return () => {
if (client) {
topicHandlers.forEach((th) => {
client.unsubscribe(th.topic);
});
client.end();
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}
export default useMqtt;