0

I think this is a trivial use case but I am still getting to grips with aspects of Flux and React. In my example I am using Reflux and React Router.

I have a basic component that displays the details of a sales lead. Using the lead id from the URL parameter, it makes a call to my service to get the lead:

var React = require('react'),
    Reflux = require('reflux');

var leadStore = require('../stores/lead'),
    actions = require('../actions');

var Lead = React.createClass({
  render : function () {
    var p = this.props.lead;

    return (
      <div>
        <h2>{p.details}</h2>
        <p>{p.description}</p>
      </div>
    );
  }
});

module.exports = React.createClass({
  mixins: [Reflux.connect(leadStore)],

  componentDidMount : function () {
    actions.loadLead(this.props.routeParams.id);
  },

  render : function () {
    if (!this.state.lead) {
      return (
        <Lead lead={this.state.lead} />
      );
    }

    return (
      <div>Loading</div>
    );
  }
});

If I don't include the conditional check then on the first pass the render method will fire and kick off an error because there's nothing in state. I could set some default state parameters but what I would ultimately like to do is show a pre-loader.

The approach I've taken feels wrong and I was wondering what the common practice was for this situation? All the examples I've seen use default states or pre-load mixins. I'm interested in knowing if there's a better way to make use of the component life-cycle?

backdesk
  • 1,781
  • 3
  • 22
  • 42

2 Answers2

0

Aside from if (!this.state.lead) should be if (this.state.lead) it looks ok. Another way would be.

module.exports = React.createClass({
  mixins: [Reflux.connect(leadStore)],

  componentDidMount : function () {
    actions.loadLead(this.props.routeParams.id);
  },

  render : function () {
    var returnIt;
    if (this.state.lead) {
      returnIt = (<Lead lead={this.state.lead} />);
    } else {
      returnIt = (<div>Loading</div>);
    }
    return (returnIt);
  }
});
J. Mark Stevens
  • 4,911
  • 2
  • 13
  • 18
0

React Wait to Render is worth checking out. It's a tiny component that will display a loader until all of the component's props are defined, e.g. while we wait for lead data. Good for keeping the render clean, as easy as:

<WaitToRender
  wrappedComponent={Lead}
  loadingIndicator={LoadingComponent}
  lead={this.state.lead} />

You can also use it to decorate your Lead component.

Jan Klimo
  • 4,643
  • 2
  • 36
  • 42