I have a mosquitto MQTT broker on a Raspberry Pi. I have some topics from a client in this format SolutionCommand/state as an array 110001.

In other hand I can invoke some publish topics like SolutionControl/WP it can be on or off. So the MQTT client would subscribe to SolutionCommand/state first of all and publish to SolutionControl/WP after processing the value of what was received. But, Here while processing how can I hold on the value of switch until receiving the current value from SolutionCommand/state this process takes 7s to received the value.

The question is how can I hold on the state after publish for 7s?

Here is my code bellow:

const client = new Paho.MQTT.Client(process.REACT_APP_HOST, Number(process.REACT_APP_PORT), clientID);

              cleanSession : false, 
              onSuccess : .... 
        }, [client])

        const onConnect = () => {
          client.subscribe(topic1,  { qos: 1 });

 const onMessageArrived = (payload)=> {
          if(payload.payloadString[0] == 1)
          else if(payload.payloadString[0] == 0){
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);
  • 1
    Is there a problem with keeping it in a variable?
    – romkey
    Jan 20, 2022 at 14:59
  • Yeah I had this problem If I send publish ON I wanna keep the switch true, in my case it it's turned off cause in subscribe it still sending OFF
    – Kindth
    Jan 20, 2022 at 15:04

2 Answers 2


I suggest you store it in a local variable and then start a time which will time out after a period longer than the expected response time.

If the local variable is set and the button is pressed again, then either ignore it it or send the new message to toggle the state the other way, depending on your design. You would then restart the timer

If you get an update message before the timeout, then cancel the timer and update the state based on the message. If you reach the timeout then you have to assume the command failed and the device didn't change state.


The solution was is if the button is pressed I stoped receiving data until the new one comes

onMessageArrived =  (payload)=> {
            if(this.state.isPressed) {
                this.setState({isPressed: false})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.