ElJefeJames ElJefeJames - 1 month ago 6
React JSX Question

Why can't I access React state within Tracker.Autorun?

This one has me stumped, I'm using a Tracker.autorun function to listen for when my Mongo subscription is ready for querying (per suggestion on this previous Meteor subscribe callback). This seems to work ok in that it triggers after a couple seconds, indicating that the meteor subscription is ready. However when I try to check state within the Tracker.autorun function, this.state is undefined. Am I missing something obvious? Is there a better pattern for this? I've been running into more and more of these issues and am starting to ponder moving onto redux... Any advice greatly appreciated!!

export default class BulkMapWrapper extends TrackerReact(React.Component) {

constructor() {
super();
this.state = {
}

}

componentDidMount(){
const subscription = Meteor.subscribe("allAuthors",{sort: {_id:-1}})
this.state = {
ready: subscription.ready(),
authorData: subscription
}

Tracker.autorun(function(){
if (subscription.ready()) {
console.log("the subscription is ready");
console.log(this.state) //this is undefined
}

Answer

I am accessing my states in Meteor Tracker with the arrow function like this:

Tracker.autorun(() => {
    if (subscription.ready()) {
        console.log("the subscription is ready");
        console.log(this.state)  //this is undefined
     }
 });

Besides this I initialize my states in the constructor and then set them with this.setState() in componentWillMount()

Comments