How to add reactivity to this function?


I have react component which renders a table.

I’m subscribing to collection with withTracker:

export default withTracker(() => {
  const subscription = Meteor.subscribe('documents');
  const offersSubscription = Meteor.subscribe('offers.all');
  return {
    loading: !subscription.ready(),
    documents: DocumentsCollection.find({}, { sort: { createdAt: -1 } }).fetch(),

Now the problem is that when i’m rendering the table I want to count number of related entries from other subscription(offers) and for that i’m using function:

const countOfOffers = (orderID) => {
  return OfferCollection.find({ orderID: orderID }).count()

and then calling this function:

            _id, title, createdAt, updatedAt, owner
          }) => (
              <tr key={_id}>

this obviously isn’t reactive. i.e when offer gets added the count in my react component will not update, it will only update when I reload the page. Whats the approach to make this also reactive?

You are right, .count() is not reactive.
There are few options:

  1. Use tmeasday:publish-counts extension.
  2. Create a collection store that count number and update it every time you make a change.

I prefer the option #2.

If you have all the records available on the client that you need to count then this is pretty simple to fix.

const countOfOffers = (orderID) => {
  return OfferCollection.find({ orderID: orderID }).fetch().length