How to detect changes to a collection on the client


#1

Hello,

I’m making a messages collection on the client. I need to be able to watch it (on the client side) so that I know when a new message is added. Then I can show it to the user. Is there any way to do this?

Thanks!


#2

You don’t need to “watch” it per-se, just:

  • create a publication for the messages collection
  • on the client subscribe to it
  • in a template/react component/container call const messagesArray = messages.find({}).fetch()
  • use said array to display the messages and gaze in wonder as it reactively updates with all messages that are added!

#3

There are a couple of options.

If you simply use a mongo query into messages as the return from a helper in blaze, then that query will be reactive and will automatically update.

If you are using other tools, there is Tracker.autorun which will automatically re-run the function passed into it if anything in it changes state (including a collection being modified).

Finally there is http://docs.meteor.com/#/full/observe which works on both server and client. You can “observe” a collection causing callbacks to be fired as it mutates.


#4

this is going on my QOTD board!


#5

I think the observe method was what I was looking for.

Thanks for the help!