mqtt-react-hooks icon indicating copy to clipboard operation
mqtt-react-hooks copied to clipboard

connectionStatus does not change when the mqtt server closes the connection

Open ToshioMagic opened this issue 3 years ago • 0 comments

I've got a mosquitto broker set up on my machine that exposes a websocket on port 9001. Here's my configuration file contents:

mosquitto.conf

allow_zero_length_clientid true
max_keepalive 65535
listener 1883
protocol mqtt
listener 1884 localhost
protocol mqtt
listener 9001
protocol websockets
require_certificate false
log_type all
websockets_log_level 1
allow_anonymous true

I have a very simple application that I believe others have used before to point out issues with connectionStatus.

App.tsx:

import { IClientOptions } from 'mqtt';
import { Connector } from 'mqtt-react-hooks';
import Status from './Status';

const options: IClientOptions = {keepalive: 10, clientId: 'MyClient'};
const brokerUrl = "ws://localhost:9001";

function App() {

  return (
    <Connector brokerUrl={brokerUrl} options={options}>
        <Status />
    </Connector>
  );
}

export default App;

Status.tsx:

import { useMqttState } from 'mqtt-react-hooks';

const Status = () => {
    const {connectionStatus} = useMqttState();

    return (
        <div>{connectionStatus}</div>
    );
}

export default Status;

If start with the mosquitto broker turned off, then turn it on, the page will correctly show the Reconnecting, Offline, and Connected connectionStatuses (in that order). I also get a websocket console error while the mosquitto broker is offline.

However, once I CTRL+C to kill the mosquitto broker, the connectionStatus continues to be shown as Connected, even though it is very obviously Offline.

In order to address this, I completely removed the mountedRef from Connector.tsx. I didn't understand what the point of this was. Likely because I'm so new to React. Once I removed all lines referencing mountedRef, I also added two more mqtt.on lines inside the useCallback to handle disconnect and close.

ToshioMagic avatar Jan 07 '22 17:01 ToshioMagic