How can I make data from MongoDB reactive in my React component?


#1

I’ve been browsing some similar questions and think I have a general idea, but I’m not sure how to proceed in making data that I take from MongoDB and make it reactive on my React component.

Essentially, I subscribe to my DB via createContainer() in the parent component:

export default createContainer(() => {
const handle = Meteor.subscribe("iData");
const loading = !handle.ready();
  return {
    questions: !loading && questions.length > 0 ? questions : []
  };
}, App);

I pass the this.props.questions data from parent App component into a Questions component. Then, in the questions component, I manipulate the data and do some transformations to get the data in the required format of values. This data is manipulated in the componentWillMount() method, so it’s set into a state instance and ready to use when the component is fully rendered.

componentWillMount(){
    let obj = this.props.aggregate // Passed from parent
    let choice;
    for(let key in obj){
      if(key === this.props.option){
        choice = obj[key];
        break;
      }
    };

    let total = 0;
    for(let key in obj){
      total += obj[key];
    }
  let uniq = shortRandomizer();
  this.setState({choice: choice, total: total, randomId: uniq});

};

So now, I use the state variable in the render() component to show data to the user, but the state never changes when the user input changes and when the MongoDB query changes, therefore not making it reactive in the UI. I console logged everything and changes are noticed, except for the state variables.

The render() method is not reactive, so I even tried to use Tracker.autorun in the render() method, but didn’t get it to work.

This is probably because componentWillMount() only fires once and state therefore won’t change when props change. But I’m not sure how to go about making this reactive like I do in Blaze using Tracker.autorun in the onRendered() template method.

Any help would be appreciated.