React Hooks
Cerebellum provides a set of custom hooks that simplify interaction with the Cerebellum instance. These hooks handle connections to channels and presence management. The hooks available are:
useChannel
usePresence
For most users, the hooks mentioned above will be sufficient for their needs. However, if you require more advanced control over the Cerebellum instance, you can use the useCerebellum
hook to access the Cerebellum instance directly. Allowing access to all of the methods and properties listed in the following general, channel, and presence method sections
useChannel
const {publish, channelName} = useChannel(channelName: string, callback?: (message: Message) => any): Channel
Description
Subscribes to a specific channel and returns a publish
function that can be used to publish messages to the channel, and a channelName
that represents the name of the channel. If a callback function is provided, it will be invoked when a new message is received in the channel.
Note, that all messages including those sent by the current sender will be received by the callback function.
Arguments
-
channelName
: string- Description: The name of the channel to subscribe to and publish messages on.
callback?: (message: Message) => any
- Description: An optional callback function that will be executed when a new message is received. The function receives a
Message
object.
-
Callback Argument:
message: Message
-
Description: The callback function receives a
Message
object containing details of the new message. -
The
Message
interface is defined as follows:interface Message {
content: any;
createdAt: string;
socketId: string;
}
-
Return Type - channelName
: string - publish
: (message: any) => void - Description: The publish
takes an argument and sends it to the current channel.
Example
import { useChannel } from "@cerebellum/sdk";
const MyComponent = () => {
const [messages, setMessages] = useState([]);
const [messageField, setMessageField] = useState("");
const { channelName, publish } = useChannel("general", (message) => {
setMessages((prevMessages) => [...prevMessages, message]);
});
};
const sendMessage = () => {
publish(messageField);
setMessageField("");
};
return (
<div>
<h1>Messages</h1>
<ul>
{messages.map((message) => (
<li key={message.createdAt}>{message.content}</li>
))}
</ul>
<input
type="text"
placeholder="Enter a message"
onChange={(event) => {
setMessageField(event.target.value);
}}
/>
<button onClick={sendMessage}>Publish Message</button>
</div>
);
Explanation
In this example, the useChannel
hook is imported from the Cerebellum SDK. It is used to subscribe to the "general" channel and publish messages to it. Every time a message is received by the channel, the onMessage
callback function is executed with the received message as an argument. Lastly, the sendMessage
function is invoked, a new message is sent to the cerebellum servers to be published to the channel.
usePresence
Arguments
-
channelName: string
- Description: The name of the channel to subscribe to presence events for.
initialUserInfo: NewState
- Description: An object representing the initial presence information for the user. This is the information that the user will send to be entered into the presence set.
- Note that the
NewState
interface is defined as follows. That the values of a state object are always strings.
interface NewState {
[key: string]: string;
}- Return Type
-
presenceData: []State
- Description: This will be an array of
State
objects representing the state of the current users in the presenece set. - An example of the
State
interface is defined as follows:
interface State {
[key: string]: string;
socketId: string;
}- Note that a unique
socketId
for each user will be included for each user in the presence set.
- Description: This will be an array of
-
updateStatus: (state: State) => void
- Description: A function that can be used to update the presence information for the user. This function takes a
NewState
object as an argument and updates the presence information for the user. Note that theNewState
interface is defined as follows. ThesocketId
of the user does not need to be included in theNewState
object. It will be automatically taken care of by the Cerebellum SDK. You just need to include the inormation that you want to update. - The
NewState
interface is defined as follows. That the values of a state object are always strings.
interface NewState {
[key: string]: string;
} - Description: A function that can be used to update the presence information for the user. This function takes a
Example
import { usePresence } from "@cerebellum/sdk";
const MyComponent = () => {
const [username, setUsername] = useState("alice");
const { presenceData, updateStatus } = usePresence("status", {
username,
status: "online",
});
return (
<div>
<h1>Presence Data</h1>
<ul>
{presenceData.map((data) => (
<li key={data.socketId}>
{data.username}: {data.status}
</li>
))}
</ul>
<p>Status: {presenceData.status}</p>
<button onClick={() => updateStatus({ status: "offline" })}>
Update Status
Explanation
- In this example,
usePresence
is imported from the Cerebellum SDK. It is used to subscribe to the "status" channel. When theusePresence
hooks is called, the intial state for the userAlice
is passed as an argument, with the status set toonline
. - The returned object contains the
presenceData
andupdateStatus
properties. - The
presenceData
property is an Array ofState
objects representing the current presence information for the users in the channel. It will be automatically updated when a user joins, leaves or updates their presence information. - The
updateStatus
property is a function that can be used to update the presence information for a user in the channel. You will pass in aNewState
object as an argument, and the function will update the presence information for the user, also letting everyone else know in the presence set that the user has updated their status. - When the component unmounts, or if the user is disconnected, the
usePresence
hook will automatically unsubscribe from the presence set, and let everyone know that the user has left the presence set.
useCerebellum
The useCerebellum
hook is used to access the Cerebellum instance directly. This hook can be used to access the Cerebellum instance and its methods directly. It is useful if you need to perform additional operations with the Cerebellum instance, that are not provided by the react hooks. The most comonon use case for this hook is to access the cerebellum
instance to retrieve the past mesasges for a channel that is using the useChannel
hook.
import { useCerebellum } from "@cerebellum/sdk";
const MyComponent = () => {
const cerebellum = useCerebellum();
const [pastMessages, setPastMessages] = useState([]);
const getPastMessages = async () => {
const messages = await cerebellum.getPastMessages("general", {
limit: 10,
sortDirection: "descending",
});
setPastMessages(messages.contents);
};
return (
<div>
<h1>Past Messages</h1>
<ul>
{pastMessages.map((message) => (
<li key={message.createdAt}>{message.content}</li>
))}
</ul>
<button onClick={getPastMessages}>Get Past Messages</button>);
</div>
);
};
Explanation
- In this example,
useCerebellum
is imported from the Cerebellum SDK. It is used to access the Cerebellum instance directly. When theuseCerebellum
hooks is called, the Cerebellum instance is returned. - The
getPastMessages
function is used to retrieve the past messages from the "general" channel. It is called when the button is clicked. Once the messages are retrieved, they are displayed in the interface for the user.