Video SDK usePubsub Hook - React Native
usePubSub Hook
usePubSub takes all the properties and events as parameters and returns all the properties and methods to work pubsub instance.
usePubSub example
import { usePubSub } from "@videosdk.live/react-native-sdk";
var topic = "CHAT";
function onMessageReceived(message) {
console.log("New Message:", message);
}
function onOldMessagesReceived(messages, { isLast }) {
console.log("Old Messages:", messages, "isLast:", isLast);
}
const { publish, messages } = usePubSub(topic, {
onMessageReceived,
onOldMessagesReceived,
});
Parameters
topic
-
type :
String -
Represents the topic for which you are publishing and getting a message.
onMessageReceived
onMessageReceived()will be triggered when a new message is published for the subscribed topic with the message object.
onBatchReceived
onBatchReceived()will be triggered with an array of new message objects. It receives the same messages asonMessageReceived(), grouped together, so you can update your state once per batch.
onOldMessagesReceived
-
onOldMessagesReceived()will be triggered when you subscribe to the topic and will receive the old messages present for that topic as an array of message objects. Long histories arrive in several batches. The second argument hasisLast, which istrueon the last batch. It is not triggered when the topic has no old messages. -
messagepublished withpersistastruewill only be available through this callback.
onMessageDrop
-
onMessageDrop()will be triggered when new messages for the topic could not be delivered, for example because they arrived faster than your app could receive them, or because ofnewMessageLimit. It receives{ droppedCount }, the number of messages that were not delivered. -
It is not triggered when
realtimeOverflowis"drop".
properties
-
type :
Object -
Optional third argument of
usePubSub. You can specify following properties.oldMessageLimit(number): How many old messages to receive when you subscribe.0receives none, and a positive number receives that many of the most recent messages.-1(default) receives all old messages.realtimeOverflow("queue"|"drop", orConstants.RealtimeOverflow): What happens when new messages arrive faster than they can be delivered."queue"(default) holds them so that you can catch up, and reports any loss throughonMessageDrop()."drop"keeps the newest messages and discards the rest.maxQueue(number): With"queue", how many batches of messages can wait while you catch up. Default:70, up to200. It cannot be used with"drop".newMessageLimit(number): The maximum number of new messages you receive every 500 ms. Extra messages are skipped and reported throughonMessageDrop().0(default) means no limit.maxMessages(number): The maximum number of messages kept inmessages. The oldest messages are removed first. By default, there is no limit.bufferMessages(boolean): Whenfalse,messagesstays empty and messages reach only your callbacks. Default:true.
Call usePubSub once per topic and pass messages and publish to the components that need them. Another usePubSub for a topic that is already subscribed shares that subscription, so its oldMessageLimit, realtimeOverflow, maxQueue and newMessageLimit are not applied.
Example
const { publish, messages } = usePubSub(
"CHAT",
{
onBatchReceived: (batch) => {
console.log("New messages:", batch.length);
},
onMessageDrop: ({ droppedCount }) => {
console.log("Messages not delivered:", droppedCount);
},
},
{
oldMessageLimit: 50,
maxMessages: 100,
}
);
Returns
publish()
publish()is used to publish the message for the particulartopic.
Parameters
message
-
type :
String -
Message that has been published on the specific topic.
options
-
type :
Object -
This specifies the options for publish. You can specify following properties.
persist: Whenpersistis set totrue, that message will be retained for upcoming participants.sendOnly: An array ofparticipantIdstrings. If you want to send a message to specific participants, you can pass their respectiveparticipantIdhere. If you don't provide any IDs, the message will be sent to all participants by default.
payload
-
type :
Object -
If you need to include additional information along with a message, you can pass here.
message must be a string, and payload must be an object.
Returns
Promise<void>. It rejects with:ERROR_ACTION_PERFORMED_BEFORE_ROOM_JOINEDwhen the room is not joined yet.ERROR_ROOM_RECONNECTINGwhile the room is reconnecting.ERROR_INVALID_PARAMETERwhenmessageis not a string orpayloadis not an object.PUBSUB_PUBLISH_FAILEDwhen the request times out or the server returns an error.
Example
const { publish, messages } = usePubSub("CHAT");
const sendMessage = async (message) => {
try {
await publish(message, { persist: true });
} catch (error) {
console.error("Failed to send message:", error);
}
};
sendMessage("Hello");
messages
-
messagesis an array of message objects. It holds the old messages received when you subscribed, followed by the new messages received since then. -
Use
maxMessagesto limit its size, or setbufferMessagestofalseto keep it empty.
{
id: String,
message: String,
senderId: String,
senderName: String,
timestamp: Number, // milliseconds since the Unix epoch
topic: String,
payload: Object,
}
Got a Question? Ask us on discord

