Skip to main content

Real-time push

CloudBase database supports listening for update events of data that matches the query criteria in collections.

Classic mode only

The realtime database is a classic-mode capability; PG-mode environments have no watch(). To listen to table changes in PG mode, use app.realtime().

PostgreSQL table changes, Broadcast, and Presence

Keep using watch() on this page for document-database collections. For Broadcast / Presence / PostgreSQL CDC, use JS SDK app.realtime().

Setting Up a Listener​

Use the watch() method to set up a listener, which returns a watcher object for closing the listener.

Any change in the documents that meet the conditions will trigger the onChange callback.

// 1. Get the database reference
const db = wx.cloud.database();

const watcher = db
.collection("todos")
.where({
// query...
})
.watch({
onChange: function(snapshot) {
console.log("snapshot", snapshot);
},
onError: function(err) {
console.error("the watch closed because of error", err);
}
});

Closing the Listener​

Call watcher.close() to close the listener.