Skip to main content
Version: 1.x.x

PubSub - React

PubSub feature allows the participant to send and receive messages of the topics which he has subscribed.

note

This page uses the following asynchronous methods. Refer to their API reference for the errors each Promise may reject with, and handle these rejections appropriately based on your use case.

Methods​

publish()​

This method is use for publishing message of specific topic.

Syntax​

function publish(message: String, options: { persist: Boolean, sendOnly: [String] }, payload: Object);
Parameter NameTypeDescription
messageStringThis is the actual message, which will be published to participants, who had subscribed to a particular topic.
optionsObjectThis is an object, which provides an option, such as persist, which persists message history for upcoming participants.
payloadObjectOptional. Structured data sent alongside the message. message must be a String — to send an object, either pass it here, or JSON.stringify() it into message and JSON.parse() it on receipt.

Example​

// importing usePubSub hook from react-sdk
import { usePubSub } from "@videosdk.live/react-sdk";

// destructure publish method from usePubSub hook
const { publish } = usePubSub("CHAT");

// publish message
const message = "Hello Everyone!";
try {
await publish(message, { persist: true });
} catch (err) {
console.error("publish failed:", err);
}

Sample Code​

import { usePubSub } from "@videosdk.live/react-sdk";

const MyComponent = () => {
// CHAT Topic
const { publish, messages } = usePubSub("CHAT");

// publish message
const sendMessage = async () => {
const message = "Hello People!";
try {
await publish(message, { persist: true });
} catch (err) {
console.error("publish failed:", err);
}
};

// get latest messages
console.log("Messages : ", messages);
};
export default MyComponent;

Got a Question? Ask us on discord