Jonas Barsten Jonas Barsten - 1 month ago 13
React JSX Question

Render single document in React with Meteor

To render a list of documents, I use

.map()
on a function that returns an array from the subscription:

{this.getApplications().map( (application) => {
return application.name;
})}


But when I want to render a single document like this:

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

constructor() {
super();
this.state = {
subscription: {
applications: Meteor.subscribe('applications')
}
}
}

componentWillUnmount() {
this.state.subscription.applications.stop();
}

getSingleApplication() {

const applicationDoc = Applications.find().fetch();

if (applicationDoc) {
return applicationDoc[0];
}
}

render () {

const name = this.getSingleApplication().name;

return (
<div>
{name}
</div>
);
}
}


I get the following error:


Cannot read property 'name' of undefined


I guess I have been missing out on some basic javascript.

Or it might have to do with subscriptions not being ready at page load?

Answer

Firstly, use .findOne() when you want to find a single document. This returns an object instead of a cursor so you don't need to .fetch() or .map().

getSingleApplication() {
  return Applications.findOne(); 
}

Then you need to code defensively in case nothing is found (which can happen if your subscription isn't ready for example).

render () {

  const app = this.getSingleApplication();
  const name = app && app.name;

  if (name) { // assuming you don't want to render anything if there is no name
    return (
      <div>
        {app.name}
      </div>
    );
  }
}
Comments