How to paginate a collection withTracker?


#1

I’ve had this working before when using createContainer but when I switch over to withTracker it just returns every result in the collection instead of using the PER_PAGE limit specified in the subscription.

I want to initially only load 5 documents, then clicking the Load More button should load the next 5 and so on.

Can somebody show me where I’m going wrong please?

import { Meteor } from 'meteor/meteor';
import React, { Component } from 'react';
import { withTracker } from 'meteor/react-meteor-data';
import { FollowersCollection } from '../../imports/collections/followers';
import Follower from './singles/Follower';

const PER_PAGE = 5;

class FollowersList extends Component {

  constructor(props) {
    super(props);
  }

  componentWillMount() {
    this.page = 1;
  }

  loadFunc() {
      Meteor.subscribe('followers', PER_PAGE * (this.page + 1));
      this.page += 1;
      console.log("loading...");
  }

  render() {
    if (this.props.allfollowers && this.props.pid) {
      return (
        <div>
          <div className="follower-list">
            {this.props.allfollowers.map(follower => <Follower key={follower._id} follower={follower}/>)}
          </div>
          <button onClick={this.loadFunc.bind(this)}>Load More</button>
        </div>
      );
    }
    return null;
  }
}

export default withTracker(props => {
   Meteor.subscribe('followers', PER_PAGE);
   console.log('Subscribe from tracker');
   return {
     allfollowers: FollowersCollection.find({}).fetch()
   }
})(FollowersList);

Publish (Server side) :

Meteor.publish('followers', function(PER_PAGE) {
    return FollowersCollection.find({}, {limit: PER_PAGE});
});

NB. I’ve removed the call to fetch specific user data to simplify the code here in case you were wondering about what props.pid was. Right now I just want to get the any data returning so I can see it working before adding the logic back in.


#2

Found it… Needed to supply a default value in the publish method for PER_PAGE.

Meteor.publish('followers', function(v, PER_PAGE = 5) {
    return FollowersCollection.find({uid: v}, {limit: PER_PAGE});
});