Whats the preferred way to initialize data in getMeteorData()?


#1

I’m currently having an issue where my components are rendering twice when the page is loaded. The first time render is called, this.data is an empty object. The second time, it contains my data from the collection.

Here is the simplest version of my component that reproduces the issue:

DealDetails = React.createClass({
  mixins: [ReactMeteorData],
  getMeteorData() {
    var data = {};
    var dealId = this.props.dealId;
    var handle = Meteor.subscribe('deals', dealId);
    if (handle.ready()) {
      data.deal = Deals.findOne({
        _id: dealId
      });
    }
    return data;
  },
  render() {
    console.log(this.data)
    return (
      <div>test</div>
    )
  }
});

Is there a way to stop the initial render? This becomes annoying when I am trying to display the data on the page where it complains that the this.data.deal.dealName is undefined:

  render() {
    console.log(this.data)
    return (
      <div>{this.data.deal.dealName}</div>
    )
  }

I can get around this with:

<div>{this.data.deal ? this.data.deal.dealName : null}</div>

but wonder if there is a more elegant way of handling this.


#2

just have a loading spinner when the page is loading? you already have the handle.ready() func, so it should be easy.


#3

The render would still execute twice and I would have to handle the undefined like in the last example. I actually do have a semantic ui spinner which works really well and disappears when handle is ready.

Is it possible to delay the component render until handle is ready?


#4

No,
but you can return different html before and after.


#5

You can return the ready state from getMeteorData and use that to render parts of the UI conditionally, like so: https://github.com/meteor/react-packages/blob/c9b1f285c438a399685dc7da7f43ea2bb6697eda/examples/react-todos/client/components/AppBody.jsx#L121-L123