title: React redux dispatch action to connect to mqtt
body: <p>I am building an react application to connect to and display data from a MQTT server.</p>
  
  <p>I have implemented the basic connection code in <code>mqtt/actions.js</code> See below:</p>
  
  <pre><code>const client = mqtt.connect(options);
  
  client.on('connect', function () {
    mqttConnectionState('MQTT_CONNECTED')
  
    client.subscribe(['btemp', 'otemp'], (err, granted) =&gt; {
      if (err) alert(err)
      console.log(`Subscribed to: otemp &amp; btemp topics`)
    })
  })
  
  client.on('message', function (topic, message) {
    updateTemp({topic: topic, value: message.toString()})
  });
  
  const mqttConnectionState = (action, err = null) =&gt; {
    return {
      type: action,
      payload: err
    }
  }
  </code></pre>
  
  <p>I am looking to on button press initiate the mqtt connection and then dispatch a connection success event.</p>
  
  <p>However with the above code I am unsure exactly how this would work.</p>
  
  <p>I could move the connect line <code>const client = mqtt.connect(options);</code> to a function and run that function on button click but then then the <code>client.on</code> functions will not be able to see the <code>client const</code>.</p>
  
  <p>How is best to approach this?</p>
  
  <p>I am using React.JS, Redux and the MQTT.JS libraries.</p>
  
  <p>Update: Trying to dispatch and action when a message is received</p>
  
  <p>Reducer:</p>
  
  <pre><code>const createClient = () =&gt; {
    const client = mqtt.connect(options);
  
    client.on('connect', function () {
      mqttConnectionState('MQTT_CONNECTED')
  
      client.subscribe(['btemp', 'otemp'], (err, granted) =&gt; {
        if (err) alert(err)
        console.log(`Subscribed to: otemp &amp; btemp topics`)
      });
    });
  
    client.on('message', (topic, message) =&gt; {
      console.log('message received from mqtt')
      processMessage({topic, message})
    })
  
    return client;
  }
  
  case MESSAGE_RECEIVED:
        console.log('message received')
        messageReceived(payload)
  
        return state;
  </code></pre>
  
  <p>Actions:</p>
  
  <pre><code>export const processMessage = (data) =&gt; dispatch =&gt; {
    console.log('Processing Message')
    return {
      type: 'MESSAGE_RECEIVED',
      payload: data
    }
  }
  </code></pre>
  
  <p><code>message received from mqtt</code> log each time a message arrives, however <code>processMessage({topic, message})</code> never executes as <code>Processing Message</code> never logs to the console</p>