How to change react component state when meteor data loaded?


#1

I have some meteor data, and need set state, when data is loaded. How? Please help.


#2

they recommend use this.data instead of this.state in some cases.

Posts = new Mongo.Collection('posts');

PostsContainer = React.createClass({
	mixins: [ReactMeteorData],
	getInitialState() {
		return {
			inc: 10,
			limit: 10
		};
	},	
	getMeteorData() {
		var fetch = [this.filter(), this.option()];
		var isReady = Meteor.subscribe('posts', ...fetch).ready();
		return {
			isReady: isReady,
			posts: Posts.find(...fetch).fetch()
		}
	},

	filter(){
		return {};
	},
	
	option() {
		return {
			limit: this.state.limit,
			sort: {
				createdAt: -1
			}
		};
	},

	render() {
		return (
			<div>
				{!this.data.isReady ? <h3>Loading...</h3> : null}
				{this.data.posts.map(this.renderPost)}
				<div>
					<button onClick={() => {
						this.setState({limit: this.state.limit + this.state.inc});
					}}>
						Load more
					</button>
				</div>
			</div>
		);
	},

	renderPost(post, key) {
		return (
			<div key={key}>
				<h3>{post.title}</h3>
				<p>{post.content}</p>
				<hr />
			</div>
		);
	}
});

if(Meteor.isServer) {
	// init data
	Posts.remove({});
	_.each(_.range(0, 100), (i) => {
		Posts.insert({
			title: `post title ${i}`, 
			content: `post content ${i}`, 
			createdAt: new Date()
		});
	});

	Meteor.publish('posts', function(filter, option) {
		console.log(filter, option)
		Meteor._sleepForMs(2000);
		return Posts.find(filter, option);
	});
}

if(Meteor.isClient) {
	Meteor.startup(() => React.render(<PostsContainer />, document.body));
}