Multiple Subscriptions in Nested Components (React)


I have a simple project in React. I’ve run into an issue regarding multiple subscriptions to the same publication in different view layers.

The basic structure is a MainLayout Component, with a NavigationBar component, and also a content prop to render my individual ‘pages’.

One of these ‘pages’ contains a subscription:


to publication:

Meteor.publish('example', (query) => { if (query) { let regex = new RegExp(query, 'i'); return Example.find({field: regex}) } else { return Example.find({}) } })

As you can see the page returns the whole collection, since there is no argument specified.

I now want to implement a search function in my NavigationBar component. This will supply an argument to the subscription so that only the matched documents will be returned.

However because the collection I am searching through is the same as the one that I am subscribing to in the content, I keep getting the entire collection returned when performing the search. It seems the filtered subscription result is overridden by


Is this expected behaviour? Is the only way to resolve this to move these two subscriptions into separate renders?



That is normal behaviour, the subscriptions compound. In the same collection one subscription might return objects a,b and c, another might return d, e and f. On the client, running both subscriptions and doing a find() on the collection will return a, b, c, d, e and f.

The solution for this is to not simply do a find() on the client, but replicate your query. So if you want to do search through regex instead of relying on the server to deliver the correct data and only that data, you write Example.find({field: regex}) on the client-side to return only the data you need.

Furthermore, if you are already subscribing to the whole collection, at that point doing a separate subscription for the regex only becomes unnecessary. You can simply subscribe to the whole collection and do the query client-side as mentioned above as the data on your client-side cache will have the same data in both cases.



Don’t know how I missed the obvious logic that I’m trying to subscribe to a subset of data that I’m already rendering…