1

I wish to show a modal dialog box (such as an alert()) every time a Meteor subscription, tracked in React with withTracker, changes.

I have tried using Tracker.autorun to track changes but cannot work out where in the code to place it. It does not seem to work in the Component constructor and runs every time if placed in render().

This is an outline of what my code looks like:

class Foo extends Component {
    render() {
        return (
            <h1>Example Header</h1>
            { this.maybeShowAlert() }
        );
    }

    maybeShowAlert() {
       // ONLY if bar has been updated
       alert('bar has changed');
    }
}

export default withTracker(() => {

    Meteor.subscribe('bar')

    return {
        bar: Bar.findOne({})
    };
})(Foo);


Tintin
  • 547
  • 5
  • 17

2 Answers2

6

Haven't used Meteor before, but if you want to do things in response to state/prop changes then componentDidUpdate() is the lifecycle method for it. E.g.

componentDidUpdate(prevProps) {
    if (this.props.bar !== prevProps.bar {
        // bar prop has changed
        alert("bar changed);
    }
}
Jayce444
  • 8,725
  • 3
  • 27
  • 43
1

If you're going to use Tracker.autorun, then the best place to call that is in componentDidMount, because it's called only once after the component has been mounted. You only need to call the tracker function once since the tracker function will rerun whenever the reactive data sources that it depends on ever changes. In the tracker function is where you will call maybeShowAlert depending on the value of bar like so,

componentDidMount() {
    Tracker.autorun(() => {
        let bar = this.props.bar;
        if (bar) {
            this.maybeShowAlert();
        }
    }
}
Chris Gong
  • 8,031
  • 4
  • 30
  • 51