How to add reactivity to this function?

Hi,

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(),
  };
})(Documents);

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:

{documents.map(({
            _id, title, createdAt, updatedAt, owner
          }) => (
              <tr key={_id}>
                <td>{title}</td>
                <td>{countOfOffers(_id)}</td>

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
}