Meteor Publish and Subscribe with React Components

March 01, 2016 0 Comments

Publications in a parent component can be passed down to children components. Duplicating the subscription in a child component is bad because you're already subscribed.

Overview

When working in teams, individuals are given discrete parts of an application to implement features in. Problems arise when they fail to look at the application as a whole. They might look at snippets online and copy and paste code into their component, logic that is already defined higher up in containing components. Let's look at how we publish and subscribe to data.

Publications

Meteor takes the traditional way of client server communications and introduces a fundamental paradox. In typical applications, the server houses your data. The client determines what kind of data they need in a request, and parse the response. In Meteor the server determines what they will send in the form of a publication. We protect sensitive data by publishing it to only authorized users. Calling Meteor.publish will register your publication and return the queried collection. In this example we're publishing a list of data in the specified category.

Meteor.publish(‘lists’, (() => {  
  Lists.find({ category: category })
})

Subscriptions

We need a way to subscribe to this data and get updates whenever this data changes. To do this we subscribe to this publication and tell it what we're subscribing to. This is how we limit the data in our client.

Meteor.subscribe(‘lists’, (() => {  
  return Lists.find({ category: ‘recipes’ }, {limit: 4})
})

React Components

The parent component can define the mixin. Then getMeteorMethods will return data in this.data. Your child components don't need to use the mixin, because this is defined up top. With a large application, you may have lots of subscriptions.


Tag cloud