How to Use MQTT in the React Native Project

Create a New React Native Project

npm install @react-native-async-storage/async-storage @rneui/base @rneui/themed

Install the MQTT Client Module

npm install react_native_mqtt

How to Use MQTT Client Module

init({
size: 10000,
storageBackend: AsyncStorage,
defaultExpires: 1000 * 3600 * 24,
enableCache: true,
sync : {}
});
const options = {
host: 'broker.emqx.io',
port: 8083,
path: '/testTopic',
id: 'id_' + parseInt(Math.random()*100000)
};
client = new Paho.MQTT.Client(options.host, options.port, options.path);
connect = () => {
this.setState(
{ status: 'isFetching' },
() => {
client.connect({
onSuccess: this.onConnect,
useSSL: false,
timeout: 3,
onFailure: this.onFailure
});
}
);
}
subscribeTopic = () => {
this.setState(
{ subscribedTopic: this.state.topic },
() => {
client.subscribe(this.state.subscribedTopic, { qos: 0 });
}
);
}
sendMessage = () =>{
var message = new Paho.MQTT.Message(options.id + ':' + this.state.message);
message.destinationName = this.state.subscribedTopic;
client.send(message);
}
unSubscribeTopic = () => {
client.unsubscribe(this.state.subscribedTopic);
this.setState({ subscribedTopic: '' });
}

Running the Project

npx react-native start
npx react-native run-ios

MQTT Connection Test

Summary

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store