How to detect changes to a collection on the client

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!

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!
1 Like

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.

2 Likes

this is going on my QOTD board!

1 Like

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

Thanks for the help!