SOLVED: Meteor.subscribe in React component constructor stopping unexpectedly


#1

EDIT: My example code actually works as I’d expect it to. There’s something else in my actual code that is prematurely stopping my subscription. Will post findings when I have them.


Given the following component:

class MyComp extends Component {
  constructor(props) {
    super(props);

    const handle = Meteor.subscribe('foo', {
      onReady: () => { console.log('ready'); },
      onStop: (e) => { console.log('stopped, e: ', e); }
    });
    ...
  }
  ...
}

When I render this component, onStop is called with no args and I’m not really sure why. I log that the publication is called on the server. No errors are thrown there. If I call the subscription from componentWillMount, same thing: sub is stopped unexpectedly.

When I move the same subscription outside of the constructor (and class definition altogether), everything works fine and the subscription’s onReady callback is called.

I’m aware of React Meteor Data, et. al. I’m just trying to build a slight variation on that for my needs.

Is there something about the lifecycle of a React component instance that is interfering with my subscription? Is something getting garbage collected and hence stopping the subscription?


#2

I was running my component subscription inside of another Tracker.autorun, which reactively validates user is logged in before rendering my component layout. This autorun was invalidating my subscription. I took a cue from ReactMeteorData which runs the getMeteorData function inside of a Tracker.nonreactive to prevent exactly this kind of things from happening. Works beautifully now!