Skip to main content
Version: 2.x.x

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​

usePubSub react hook
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 as onMessageReceived(), 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 has isLast, which is true on the last batch. It is not triggered when the topic has no old messages.

  • message published with persist as true will 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 of newMessageLimit. It receives { droppedCount }, the number of messages that were not delivered.

  • It is not triggered when realtimeOverflow is "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. 0 receives none, and a positive number receives that many of the most recent messages. -1 (default) receives all old messages.
    • realtimeOverflow ("queue" | "drop", or Constants.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 through onMessageDrop(). "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 to 200. 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 through onMessageDrop(). 0 (default) means no limit.
    • maxMessages (number): The maximum number of messages kept in messages. The oldest messages are removed first. By default, there is no limit.
    • bufferMessages (boolean): When false, messages stays empty and messages reach only your callbacks. Default: true.
note

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 particular topic.

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: When persist is set to true, that message will be retained for upcoming participants.
    • sendOnly: An array of participantId strings. If you want to send a message to specific participants, you can pass their respective participantId here. 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.


important

message must be a string, and payload must be an object.

Returns​

  • Promise<void>. It rejects with:
    • ERROR_ACTION_PERFORMED_BEFORE_ROOM_JOINED when the room is not joined yet.
    • ERROR_ROOM_RECONNECTING while the room is reconnecting.
    • ERROR_INVALID_PARAMETER when message is not a string or payload is not an object.
    • PUBSUB_PUBLISH_FAILED when 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​

  • messages is an array of message objects. It holds the old messages received when you subscribed, followed by the new messages received since then.

  • Use maxMessages to limit its size, or set bufferMessages to false to keep it empty.

Message Object
{
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