Presence State

Clients can set a dynamic custom state for their users on one or more channels and store it on a channel as long as the user stays subscribed.

Some examples of custom states are to add your score, game state, or location to an application if it changes frequently.

The state is transient data (it's not persisted anywhere). When the client disconnects, the state data is lost. If you require a client's state to be restored on reconnect, be sure to cache that data locally on the client. For information on how to persist data forever, refer to the Metadata documentation.

PubNub also triggers presence state-change events anytime the user's state is modified. Clients can receive these events by subscribing to presence channels. Refer to Presence Events for more details.

User ID / UUID

User ID is also referred to as UUID/uuid in some APIs and server responses but holds the value of the userId parameter you set during initialization.

Set Presence State

You can set state data for a User ID on a given channel(s) or channel group(s). By default, the User ID is the current client's User ID when this API is invoked. When setting the state on a channel group, it propagates that state to all channels contained in that channel group.

pubnub.setState(
{
state: {"mood":"pumped", "isTyping":false},
channels: ["chats.room1"],
channelGroups: ["cg_user123_friends"]
},
function (status, response) {
if (status.isError) {
console.log(status);
}
else {
console.log(response);
}
}
);

When you set the state for a client, the existing state is overwritten. Therefore, if you need to update part of the state, you must pass the complete state data payload. For this reason, it's best to keep your state data payloads from getting too large.

Get Presence State

You can get state data for any client on a given channel(s) or channel group(s) using the Get State API. This is useful to get the state of other clients based on their User ID.

pubnub.getState(
{
uuid: "anotherClientUserID",
channels: ["chats.room1"],
channelGroups: ["cg_user123_friends"]
},
function (status, response) {
// handle status, response
}
);
Last updated on