0
votes

I have issue when using npm mqtt with react. subscribe topic 'alert' to receive data publish from server then client unsubscribe this topic . after each subscribe and unsubscribe message is duplicate. The server sends 1 message; the client receives more 1 message. base on subscribe and unsubscribe increase message.

const List = () => {
  
  const listener = (topic, message) => {
    const data = JSON.parse(message.toString());
    if (topic.includes('alert')) {
      console.log(data)
    }
  };

  const subscribe = instruments => {
    client.subscribe('alert');
    client.on('message', listener);
  };

  const unsubscribe = () => {
    client.unsubscribe('alert');
    client.off('message', listener);
  };

  return (
    <div className={s.container}>
      <Button onClick={subscribe}>sub</Button>
      <Button onClick={unsubscribe}>unsub</Button>
    </div>
  );
};

export default List;
1

1 Answers

1
votes

You are subscribing/unsubscribing to different topics, so each time you click the subscribe button it will just re-add the same topic again to the list.

Also there is no need to keep adding/removing the message event listener when you subscribe/unsubscribe.