Skip to content

Infinite loop when using React context feature #113

Closed
@ffxsam

Description

@ffxsam

I've run into an infinite loop situation where basically what's happening is this:

I have a Parent component that contains two functions, showSpinner and hideSpinner, which essentially set the Parent state to spinnerVisible: true and spinnerVisible: false, respectively.

I'm using context to pass these functions down wherever they're needed:

Parent.jsx

Parent = React.createClass({
  childContextTypes: {
      spinnerVisible: React.PropTypes.bool,
      spinnerMessage: React.PropTypes.string,
      showSpinner: React.PropTypes.func,
      hideSpinner: React.PropTypes.func
  },

  getChildContext() {
        spinnerVisible: this.state.spinnerVisible,
        spinnerMessage: this.state.spinnerMessage,
        showSpinner: this.showSpinner,
        hideSpinner: this.hideSpinner
  }

  [...]

And then in a child template (we'll call Child for simplicity's sake):

  getMeteorData() {
    let handle = Meteor.subscribe('tracks');

    if (!handle.ready()) {
      this.context.showSpinner(TAPi18n.__('loadingTracks'), true);
    } else {
      this.context.hideSpinner();
      console.log('we are ready');
    }

    return {
      ready: handle.ready(),
      tracks: Tracks.find({}, {sort: {createdAt: -1}}).fetch()
    }
  },

What happens is, I get the spinner for a couple seconds while the subscription is waiting for data (I have an artificial 5-second sleep in the publication). Once it's ready, I get an infinite amount of "we are ready" messages being dumped.

The interesting thing is, if I remove this.context.hideSpinner(), I get the message just once. So apparently, when hideSpinner() is setting the Parent's state to spinnerVisible: false, it's triggering the getMeteorData method over and over. I'm guessing this might be a bug involving React's context feature, but I could be wrong.

Any help on this would be greatly appreciated!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions