I had a problem using MQTT with Paho client. I have to subscribe first to know the state of every switch then publish so after sending a message I should wait 7 second to receive the current state but here in my case it return state of previous topic & display it on my switch so the state of switch after I turned it on it turned off then after 7 second of transactions then it become ON, my question is how can I handle the state send it of Enabled1 until I received to current one (how can I stop receiving subscribe messages)?
here is my code bellow :
const client = new Paho.MQTT.Client(process.REACT_APP_HOST, Number(process.REACT_APP_PORT), clientID);
if(client){
client.connect({
cleanSession : false,
onSuccess : onConnect,
userName: process.REACT_APP_DB_NAME,
password: process.REACT_APP_PASSWORD,
onFailure : onConnectionLost,
});
}
}, [client])
const onConnect = () => {
client.subscribe(topic1, { qos: 1 });
};
const onMessageArrived = (payload)=> {
if(payload.payloadString[0] == 1)
{
setSolutionPump('ON')
setIsEnabled(true)
}
else if(payload.payloadString[0] == 0){
setSolutionPump('OFF')
setIsEnabled(false)
}
const toggleSwitch1 = () => {
const topic = "SolutionControl/WP";
if(!isEnabled1) {
setIsEnabled1(previousState => !previousState);
client.publish(topic, "on", 1);
}
else {
setIsEnabled1(previousState => !previousState);
client.publish(topic, "off", 1);
}
}