Using mqtt.js in next page #16904
-
Hi, I was trying to write a service that connects pages to an mqtt broker using MQTTjs. To repro just insert the following component into the create-next-template and change the connection info of the broker:
Regards Sebastian |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
These are untested, but I would think one of these options would work: // option 1
// keep a ref to the client so React saves a copy between renders
const clientRef = React.useRef(null)
useEffect(() => {
// access client vis clientRef.current
console.dir(${clientRef.current});
if (clientRef.current) {
console.log(`client: ${clientRef.current}`);
clientRef.current = mqtt.connect(mqttUri, options);
clientRef.current.subscribe('test');
clientRef.current.on('message', (message) => { setMessages(messages.concat(message.toString())); });
}
return () => {
// always clean up the effect if clientRef.current has a value
if (clientRef.current) {
clientRef.current.unsubscribe('test');
clientRef.current.end(clientRef.current);
}
};
});
// option 2
useEffect(() => {
const client = mqtt.connect(mqttUri, options);
client.subscribe('test');
client.on('message', (message) => { setMessages(messages.concat(message.toString())); });
return () => {
if (client) {
client.unsubscribe('test');
client.end(client);
}
};
}, []); // only run this effect on mount on the client side |
Beta Was this translation helpful? Give feedback.
These are untested, but I would think one of these options would work: