Last active
June 13, 2017 21:20
-
-
Save curranabell/e9f92fb6a21bfefffa9dc0def2046962 to your computer and use it in GitHub Desktop.
Meteor Subscribe Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Only executed on the server | |
import _ from 'lodash'; | |
import { Meteor } from 'meteor/meteor'; | |
import { Employees } from '../imports/collections/employees'; | |
import { image, helpers } from 'faker'; | |
Meteor.startup(() => { | |
//Great place to generate data | |
//Check to see if data exists in the collection | |
//See if the collection has any records | |
const numberRecords = Employees.find({}).count(); | |
console.log(numberRecords); | |
if (!numberRecords) { | |
//Generate some data... | |
_.times(5000, () => { | |
const { name, email, phone } = helpers.createCard(); | |
Employees.insert({ | |
name, email, phone, | |
avatar: image.avatar() | |
//Equivalent to: | |
//name: name; | |
//email: email, | |
//phone: phone | |
}); | |
}); | |
} | |
Meteor.publish('employees', function(per_page) { | |
return Employees.find({}, { limit: per_page }); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import { createContainer } from 'meteor/react-meteor-data'; | |
import { Employees } from '../../imports/collections/employees'; | |
import EmployeeDetail from './employee_detail'; | |
const PER_PAGE = 20; | |
class EmployeeList extends Component { | |
componentWillMount() { | |
this.page = 1; | |
} | |
handleButtonClick() { | |
Meteor.subscribe('employees', PER_PAGE * this.page + 1); | |
this.page += 1; | |
} | |
//prop.employees => an array of employee objects | |
render () { | |
return ( | |
<div> | |
<div className="employee-list"> | |
{this.props.employees.map(employee => | |
<EmployeeDetail key={employee._id} employee={employee} /> | |
)} | |
</div> | |
<button onClick={ this.handleButtonClick.bind(this) } | |
className="btn btn-primary"> | |
Load More... | |
</button> | |
</div> | |
); | |
} | |
}; | |
export default createContainer(() => { | |
// set up subscription | |
Meteor.subscribe('employees', PER_PAGE); | |
//return an object. Whatever we return will be sent to EmployeeList | |
// as props | |
return { employees: Employees.find({}).fetch() }; | |
}, EmployeeList); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment