KeKs0r / mqtt-react

React container for MQTT
47 stars 31 forks source link

How to know from which topic you received a message from? #7

Open stramike opened 6 years ago

stramike commented 6 years ago

In the documentation is showed how to access messages you receive once subscribed through props.data ; Is there a way to know from which topic the message was send from? Or is there a way to dynamically subscribe to different topics using data from the component's props? Documentation is not that clear about this. Thanks

DrSkunk commented 5 years ago

I had the same issue. The way I fixed it is by creating a custom dispatcher function like in the documentation and add the topic the data when setting the state. I'm on my phone, so let me know if you need a code example.

stramike commented 5 years ago

Thanks for sharing! I really appreciate it! A code example would be great!

DrSkunk commented 5 years ago

A quick example would be something like this. It's mainly taken from https://github.com/KeKs0r/mqtt-react/blob/master/src/subscribe.js

import { subscribe } from "mqtt-react";

// This does automatic parsing of JSON if needed, can be removed.
function parse(message) {
  try {
    const item = JSON.parse(message);
    return item;
  } catch (e) {
    return message.toString();
  }
}

function customDispatch(topic, rawMessage, packet) {
  const { state } = this;
  const message = parse(rawMessage);
  const newData = [
    {
      topic,
      message
    },
    ...state.data
  ];
  this.setState({ data: newData });
}

export default subscribe({
  topic: "@demo/test",
  dispatch: customDispatch
});

This would set props.data to an array with objects with two keys, topic and message.

Hope it helps!