mqtt-react
mqtt-react copied to clipboard
Dynamic topic subscriptions?
I'm looking to make a reusable Component, each one subscribing to a different topic. In the code examples, the subscribe function is hard-coded to a particular topic. How can I dynamically do this? Say I have an array of topics, and I wanted to do a .map() function that creates a component using subscribe(). What's the recommended way of providing the topic to the component I'm instantiating?
the subscribe method should accept a parameter (which will be the props passed to the component) like react-redux connect function .. then we can subscribe like
export default subscribe( props => { topic: props.topic })(MessageList)
as a workaround we can subscribe in the parent's component render function (Huge performance risk)
render() { this.MessageContainer = subscribe({topic:
test${this.props.me.id}})(MessageList); return ( ... <MessageContainer/> ... ) }
Any other solution ? I'm quite struggling with this.
i forked the library locally and edit the subscribe.js file .. it's easy .. you resubscribe when props change
let { topic, options } = opts topic = topic || this.props.topic;
componentWillReceiveProps(nextProps, nextContext) { topic = nextProps.topic this.subscribe();
i may create a formal PR if this is common
I would appreciate formal PR.
But I also failed to pass topic as prop to decorator.
When exporting component:
export default subscribe( props => { topic: props.topic })(MessageList)
And calling it from parent component:
<MessageList topic="/topic" />
I'm getting error:
Expected an assignment or function call and instead saw an expression no-unused-expressions
actually i pass the props in the parent component not to the decorator.
...
export default subscribe({ options: {qos:1}, dispatch: customDispatch })(Notifications)
then
<Notifications topic={xxx} />
Really interested in a solution to this. Seems like an important feature, as reusable components are a primary benefit of React. I don't want to create a new component for each topic subscription.
tks for answer ^^
An example for many topics ?