Passing Asynchronously Acquired Data To Child Props
Solution 1:
I would suggest leaving it up to the parent to decide what to do when it is in a "loading" state and leaving BigStory
as a "dumb" component that always renders the same assuming it will always receive a valid newsItem
.
In this example, I show a <LoadingComponent />
, but this could be whatever you need it to be. The concept is that BigStory
shouldn't have to worry about edge cases with "receiving invalid data".
varMain = React.createClass({
// ...render() {
const {newsItems} = this.state;
// You could do this, pass down `loading` explicitly, or maintain in stateconst loading = newsItems.length === 0;
return (
<divclassName="container"><divclassName="main-content col-sm-12"><divclassName="left-sided-lg-top-otherwise col-lg-8 col-md-12 col-sm-12 col-xs-12">
{loading
? <LoadingComponent />
: <BigStorynewsItem={newsItems[0]} />
}
</div></div></div>
);
}
});
functionBigStory(props) {
// Render as usual. This will only be used/rendered w/ a validreturn (
<divclassName="big-story col-xs-12"><h1>{props.headline}</h1>
{/* ... */}
</div>
)
}
An alternative solution (although I recommend an approach more like above) would be to always make use of the BigStory
component in the same way, but provide it a "placeholder story" when there are no stories loaded.
const placeholderNewsItem = {
headline: 'Loading...',
/* ... */
};
varMain = React.createClass({
// ...render() {
const {newsItems} = this.state;
// Conditionally pass BigStory a "placeholder" news item (i.e. with headline = 'Loading...')const newsItem = newsItems.length === 0
? placeholderNewsItem
: newsItems[0];
return (
<divclassName="container"><divclassName="main-content col-sm-12"><divclassName="left-sided-lg-top-otherwise col-lg-8 col-md-12 col-sm-12 col-xs-12"><BigStorynewsItem={newsItem} /></div></div></div>
);
}
});
Solution 2:
This is a pretty common scenario. John Carpenter's approach would work. Another approach that I use often would be to create some type of Loading
component with a spinner image (or whatever else you might use to signify that data is on its way). Then, while the client waits for the data to arrive, you can render that Loading
component. For example:
render: function () {
if (this.state.newsItems.length === 0) return<Loading />;
return (
<divclassName="container"><divclassName="main-content col-sm-12"><divclassName="left-sided-lg-top-otherwise col-lg-8 col-md-12 col-sm-12 col-xs-12"><BigStorynewsItems={this.state.newsItems[0]}/></div></div></div>
);
}
Solution 3:
One way you could do it is to set this.props.newsItems.headline
to "loading..." initially to indicate to the user that data will be coming.
Post a Comment for "Passing Asynchronously Acquired Data To Child Props"