Wix realtime API allows you to setup communication between front-end and back-end events. Let's take you would like to display a notification box on front-end when a new record is inserted into a wix collection.
Note: the realtime API does not work in editor mode
Subscribe to backend notifications
On your front-end page, create a notification box with text inside and hide it by default. Put below code on the page where you would like to receive backend notification.
First import the wix-realtime API on front-end
import * as realtime from "wix-realtime";
Subscribe to the backend notifications (this is the channel name) inside onReady function. When a users visit the page, they are subscribed to notification channel and if there is any backend notification comes, below code will call newRecord function
realtime.subscribe({ name: 'notification' }, newRecord);
Write newRecord function and capture the payload (message) coming from backend. You can then display this message in a text box for 4 seconds
async function newRecord({ payload }) {
setTimeout(function(){
$w('#txtMessage').text = payload.message;
}, 4000); // 4 seconds
}
The final code should look something like this
import * as realtime from "wix-realtime";
$w.onReady(function () {
realtime.subscribe({name: 'notification'}, newRecord);
});
async function newRecord({ payload }) {
//the {} converts payload jSON string to an object
setTimeout(function(){
$w('#txtMessage').text = payload.message;
}, 4000); // 4 seconds
//log the entire payload item to console
console.log(payload.item);
}
Publish messages to frontend
Let's take you would like to send notifications to users after a new record is inserted into property collection. Add an afterUpdate hook on property collection and open data.js
import { publish } from 'wix-realtime-backend';
export async function property_afterUpdate(item, context) {
publish(
{ name: "testPublish" },
{ response: `Record Saved`, recordId: `${item._id}` },
//entire thing is sent as payload to FE
{ includePublisher: true }
);
return item;
}
In case you would like to send entire inserted record to the frontend
import { publish } from 'wix-realtime-backend';
export async function property_afterUpdate(item, context) {
publish(
{ name: "testPublish" },
{ item }, //entire row is sent as payload to FE
{ includePublisher: true }
);
return item;
}
That's it! you can adapt the above code to push notifications from backend. The biggest benefit is that users do not have to refresh their webpage to receive backend notifications.
Some ideas to adapt above code:
Refresh a repeater on front-end
Refresh dataset on front-end
Show progress on front-end with progress bar tied to notifications
Update elements on screen once backend notification comes