Reputation: 1
I am trying to fetch data from a MQTT server using react.js and TypeScript. The server sends data from a robot every 100ms. I've already tried npm install mqtt.
I don't have much experience with MQTT, i just want to fetch the data from it
import React from "react";
import * as mqtt from "mqtt";
function App() {
let client = mqtt.connect("mqtt://test.mosquitto.org");
React.useEffect(() => {
client.on("connect", function () {
client.subscribe("presence", function (err: any) {
if (!err) {
client.publish("presence", "Hello mqtt");
}
});
});
client.on("message", function (topic: any, message: any) {
// message is Buffer
console.log(message.toString());
client.end();
});
}, []);
return <> MQQT </>;
}
export default App;
The error is constants.js:46 Uncaught ReferenceError: Buffer is not defined at ./node_modules/mqtt-packet/constants.js (constants.js:46:1)
How can I handle this properly?
import mqtt from 'mqtt'; expected data to be fetched
Upvotes: 0
Views: 492
Reputation: 461
When using vite or webpack, the import is different:
import * as mqtt from 'mqtt/dist/mqtt.min'
It's all documented: https://github.com/mqttjs/MQTT.js#vite
Upvotes: 0