How to connect to an MQTT broker in React-Native?

I am trying to integrate MQTT into my app. I was reading this post, but I can’t connect to the broker due to either using an outdated React Native MQTT library or my code being wrong. How can I successfully connect to a broker?

import init from 'react_native_mqtt';
import { AsyncStorage } from 'react-native';

init({
  size: 10000,
  storageBackend: AsyncStorage,
  defaultExpires: 1000 * 3600 * 24,
  enableCache: true,
  reconnect: true,
  sync : {
  }
});

const client = new Paho.MQTT.Client(
  "m23.cloudmqtt.com", 
  18628,
  "clientID-" + parseInt(Math.random() * 100)
);

client.connect({ 
  useSSL: true,
  userName: "username",
  password: "password"
});

function onConnect() {
  client.subscribe("topic");
}

50 thoughts on “How to connect to an MQTT broker in React-Native?”

Leave a Comment