rsnext/examples/with-mqtt-js/pages/index.tsx
Steven 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

66 lines
1.8 KiB
TypeScript

import { useState, useRef } from "react";
import type { MqttClient } from "mqtt";
import useMqtt from "../lib/useMqtt";
export default function Home() {
const [incommingMessages, setIncommingMessages] = useState<any[]>([]);
const addMessage = (message: any) => {
setIncommingMessages((incommingMessages) => [
...incommingMessages,
message,
]);
};
const clearMessages = () => {
setIncommingMessages(() => []);
};
const incommingMessageHandlers = useRef([
{
topic: "topic1",
handler: (msg: string) => {
addMessage(msg);
},
},
]);
const mqttClientRef = useRef<MqttClient | null>(null);
const setMqttClient = (client: MqttClient) => {
mqttClientRef.current = client;
};
useMqtt({
uri: process.env.NEXT_PUBLIC_MQTT_URI,
options: {
username: process.env.NEXT_PUBLIC_MQTT_USERNAME,
password: process.env.NEXT_PUBLIC_MQTT_PASSWORD,
clientId: process.env.NEXT_PUBLIC_MQTT_CLIENTID,
},
topicHandlers: incommingMessageHandlers.current,
onConnectedHandler: (client) => setMqttClient(client),
});
const publishMessages = (client: any) => {
if (!client) {
console.log("(publishMessages) Cannot publish, mqttClient: ", client);
return;
}
client.publish("topic1", "1st message from component");
};
return (
<div>
<h2>Subscribed Topics</h2>
{incommingMessageHandlers.current.map((i) => (
<p key={Math.random()}>{i.topic}</p>
))}
<h2>Incomming Messages:</h2>
{incommingMessages.map((m) => (
<p key={Math.random()}>{m.payload.toString()}</p>
))}
<button onClick={() => publishMessages(mqttClientRef.current)}>
Publish Test Messages
</button>
<button onClick={() => clearMessages()}>Clear Test Messages</button>
</div>
);
}