React V4 SDK v2.1.0
Note
This SDK version has been deprecated. A new version of the PubNub React framework 2.0 is now available. You can access it here
Get Code: Source
https://github.com/pubnub/react
Get Code: NPM
npm install --save pubnub pubnub-react
Hello World
PubNub React is a wrapper of the PubNub JavaScript SDK version 4 that adds a few extra features to simplify integration with React/React Native:
- Trigger Events:
getMessage
,getPresence
,getStatus
will make your life easier in the React world. - Autoload: An easy and fast way to recovery the history messages of your channel.
You can still use the native PubNub JavaScript SDK if you feel it's more appropriate to your situation.
Differences in usage with native JavaScript SDK
PubNub React is a wrapper of PubNub JavaScript which offers the same feature and in the same way like Javascript SDK makes, So if you have experience using Javascript SDK will be fast to learn the features included for React SDK in other way if you want to learn more about PubNub JavaScript features refer to native PubNub JavaScript SDK manual.
Differences between React and React Native
PubNub React works for both frameworks seamlessly the only difference will be how to you are going to implement all UI elements into the render()
if your app is done with React or React Native.
That's it, you are ready to start using PubNub React SDK
Hello World Example
Hello World Example using React
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
import React, { Component } from 'react';
import PubNubReact from 'pubnub-react';
export default class extends Component {
constructor(props) {
super(props);
this.pubnub = new PubNubReact({
publishKey: 'YOUR PUBLISH KEY',
subscribeKey: 'YOUR SUBSCRIBE KEY'
});
this.pubnub.init(this);
}
componentWillMount() {
this.pubnub.subscribe({
channels: ['channel1'],
withPresence: true
});
this.pubnub.getMessage('channel1', (msg) => {
console.log(msg);
});
this.pubnub.getStatus((st) => {
this.pubnub.publish({
message: 'hello world from react',
channel: 'channel1'
});
});
}
componentWillUnmount() {
this.pubnub.unsubscribe({
channels: ['channel1']
});
}
render() {
const messages = this.pubnub.getMessage('channel1');
return (
<div>
<ul>
{messages.map((m, index) => <li key={'message' + index}>{m.message}</li>)}
</ul>
</div>
);
}
}
Hello World Example using React Native
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
import React, { Component } from 'react';
import PubNubReact from 'pubnub-react';
export default class extends Component {
constructor(props) {
super(props);
this.pubnub = new PubNubReact({
publishKey: 'YOUR PUBLISH KEY',
subscribeKey: 'YOUR SUBSCRIBE KEY'
});
this.pubnub.setUUID("myUniqueUUID");
this.pubnub.init(this);
}
componentWillMount() {
this.pubnub.subscribe({
channels: ['channel1'],
withPresence: true
});
this.pubnub.getMessage('channel1', (msg) => {
console.log(msg);
});
this.pubnub.getStatus((st) => {
this.pubnub.publish({
message: 'hello world from react',
channel: 'channel1'
});
});
}
componentWillUnmount() {
this.pubnub.unsubscribe({
channels: ['channel1']
});
}
render() {
const messages = this.pubnub.getMessage('channel1');
return (
<View>
{messages.map((m, index) => <Text key={'message' + index}>{m.message}</Text>)}
</View>
);
}
}
How to use PubNubReact
In order to get the integration between your React's Component and PubNub, PubNubReact will be the way to get this without any kind of difficulty or extra job when you need render data in your UI.
Notes:
- An instance of PubNubReact can be associated to only a Component.
- Create and initialize your PubNubReact from the constructor.
- If you want to subscribe a channel automatically as soon as the component will be displayed on the screen, you will have to subscribe it from the mounting point with the usage of
componentWillMount()
provided by React. - SDK will have created three states which are handled by the instance directly and these are
pn_messages
,pn_presence
andpn_status
please only use them in reading mode if you want to use them for any reason. In addition the trigger events will give you some extra features to manage the data allocated in theses states.
import PubNubReact from 'pubnub-react';
constructor(props) {
super(props);
this.pubnub = new PubNubReact({
publishKey: 'YOUR PUBLISH KEY',
subscribeKey: 'YOUR SUBSCRIBE KEY'
});
this.pubnub.init(this);
}
componentWillMount() {
this.pubnub.subscribe({
channels: ['channel1']
});
this.pubnub.getMessage('channel1', (msg) => {
console.log(msg);
});
}
Events
Another key feature of this SDK is the ability to use trigger events, in addition to pass callbacks, getting all messages through states and inject them directly in your UI of your React\React Native Component in an easy and fast way.
Triggering and listening to events for the subscribe method
With Javascript SDK V4, you can find three different events (message, presence and status).
Triggering the events
With the trigger events you can find a way to get real time apps with PubNub React very fast because it will be resolved the synchronization between the data received and the user interface through of updating of the states to invoke the render of the React's Component.
The trigger events are methods which encapsulate the events (message
, presence
and status
) with extra functionality to offer integration and get the process of development faster because will be resolved different scenarios which you can find when you are working with React\React Native.
To execute the trigger events you have to execute the init()
method first, in this way getMessage
, getPresence
and getStatus
will be available; these trigger events have the responsibility to register a channel or a channelGroup in order to capture any real time message as soon as this is received and update the state then the Component renders automatically the user interface.
The getStatus
will only say to the Component that this has to render again if there is an update in the global state of the network.
To use getPresence
you will have to add the argument withPresence: true
when you are subscribing your channels.
this.pubnub.getStatus();
this.pubnub.getMessage('channel1');
this.pubnub.getMessage('channel2');
this.pubnub.getMessage('channelGroup1');
this.pubnub.getPresence('channel1');
this.pubnub.getPresence('channel2');
getMessage
Rendering real time messages from React
...
componentWillMount() {
this.pubnub.getMessage('channel1');
...
}
render() {
const messages = this.pubnub.getMessage('channel1');
return (
<div>
<ul>
{messages.map((m, index) => <li key={'message' + index}>{m.message}</li>)}
</ul>
</div>
);
}
...
Rendering real time messages from React Native
...
componentWillMount() {
this.pubnub.getMessage('channel1');
...
}
render() {
const messages = this.pubnub.getMessage('channel1');
return (
<View>
{messages.map((m) => <Text>{m.message}</Text>)}
</View>
);
}
...
In addition to be used to register channels or channelGroups you can also catch each message if you want to give it some kind of procedure to each message.
this.pubnub.getMessage('channel1', (msg) => {
console.log(msg);
});
When you are using getMessage
this going to keep the latest 100 messages received by default. But you can change this value when you attach the channel for first time with getMessage
.
this.pubnub.getMessage('channel1', (msg) => {
console.log(msg);
}, 20);
this.pubnub.getMessage('channel2', 30);
getPresence
Rendering presence object from react
...
componentWillMount() {
this.pubnub.getPresence('channel1', (presence) => {
console.log(presence);
});
...
}
render() {
const presence = this.pubnub.getPresence('channel1');
return (
<div>
<p>{presence.action}</p>
</div>
);
}
...
Rendering presence object from React Native
...
componentWillMount() {
this.pubnub.getPresence('channel1', (presence) => {
console.log(presence);
});
...
}
render() {
const presence = this.pubnub.getPresence('channel1');
return (
<View>
<Text>{presence.action}</Text>
</View>
);
}
...
Listening to the global status
Via the status listener, you can receive different events such as: when the network is online (PNNetworkUpCategory
), when the SDK is connected to a set of channels (PNConnectedCategory
), etc... See the list of events available in the API Reference
Rendering the global status from React
...
componentWillMount() {
this.pubnub.getStatus((status) => {
console.log(status);
});
...
}
render() {
const status = this.pubnub.getStatus();
return (
<div>
<p>{status.category}</p>
</div>
);
}
...
Rendering the global status from React Native
...
componentWillMount() {
this.pubnub.getStatus((status) => {
console.log(status);
});
...
}
render() {
const status = this.pubnub.getStatus();
return (
<View>
<Text>{status.category}</Text>
</View>
);
}
...
Cleaning and Releasing
You can execute clean to remove all message cached in the state of the Component by the instance in running time without affecting the capture of new incoming messages for the trigger events.
this.pubnub.clean('myChannel1');
this.pubnub.clean('myGroup1');
You can execute release if you want to remove all message cached and stop of capturing new incoming messages for the trigger events.
this.pubnub.release('myChannel1');
this.pubnub.release('myGroup1');
this.pubnub.release(['myChannel1', 'myChannel2']);
Getting the history with autoload
At the moment that you are subscribing a channel you can pass the optional parameter autoload this value has to contain a value from 1 to 100 in order to retrieve the last messages published in the channel. When the getMessage
is called this going to retrieve the history. You can use a callback to know when the retrieving process has finished also this will take effect inside of state pn_message which will invoke a new render in your Component.
this.pubnub.subscribe({
channels: ['myChannel1'],
triggerEvents: true,
withPresence: true,
autoload: 100
});
let messages = this.pubnub.getMessage('myChannel1', () => {
console.log(messages);
});
Copy and paste examples
In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:
Init
Instantiate a new Pubnub instance. Only the subscribeKey
is mandatory. Also include publishKey
if you intend to publish from this instance, and the secretKey
if you wish to perform PAM administrative operations from this React V4 instance.
Important
It is not a best practice to include the secretKey
in client-side code for security reasons.
When you init with secretKey
, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.
Note
Set restore
to true
to allow catch-up on front-end applications.
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
this.pubnub = new PubNubReact({
publishKey: 'YOUR PUBLISH KEY',
subscribeKey: 'YOUR SUBSCRIBE KEY',
uuid: "myUniqueUUID",
ssl: true
});
Listeners
Adding Listeners
this.pubnub.addListener({
status: (st) => {
if (st.category === "PNUnknownCategory") {
var newState = {new: 'error'};
pubnub.setState(
{
state: newState
},
function (status) {
console.log(st.errorData.message);
}
);
}
},
message: (message) => {
console.log(message);
}
});
this.pubnub.subscribe({
channels: ['my_channel']
});
Removing Listeners
var existingListener = {
message: function() {
}
}
this.pubnub.removeListener(existingListener)
Listener status events
Category | Description |
---|---|
--- | --- |
PNNetworkUpCategory | The SDK detected that the network is online. |
PNNetworkDownCategory | The SDK announces this when a connection isn't available, or when the SDK isn't able to reach the PubNub Data Stream Network. |
PNNetworkIssuesCategory | A subscribe event experienced an exception when running. The SDK isn't able to reach the PubNub Data Stream Network. This may be due to many reasons, such as: the machine or device isn't connected to the internet; the internet connection has been lost; your internet service provider is having trouble; or, perhaps the SDK is behind a proxy. |
PNReconnectedCategory | The SDK was able to reconnect to PubNub. |
PNConnectedCategory | SDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes. |
PNAccessDeniedCategory | PAM permission failure. |
PNMalformedResponseCategory | JSON parsing crashed. |
PNBadRequestCategory | The server responded with a bad response error because the request is malformed. |
PNDecryptionErrorCategory | If using decryption strategies and the decryption fails. |
PNTimeoutCategory | Failure to establish a connection to PubNub due to a timeout. |
PNRequestMessageCountExceedCategory | The SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold. |
PNUnknownCategory | Returned when the subscriber gets a non-200 HTTP response code from the server. |
Time
Call time()
to verify the client connectivity to the origin:
this.pubnub.time((status, response) => {
if (status.error) {
console.log(status.error);
} else {
console.log(response.timetoken);
}
});
Subscribe
Subscribe (listen on) a channel:
this.pubnub.subscribe({
channels: ['my_channel'],
});
Note
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Publish
Publish a message to a channel:
this.pubnub.publish(
{
message: {
such: 'object'
},
channel: 'ch1',
sendByPost: false, // true to send via POST
storeInHistory: false, //override default storage options
meta: {
"cool": "meta"
} // publish extra meta with the request
},
(status, response) => {
// handle status, response
}
);
Here Now
Get occupancy of who's here now
on the channel by UUID:
Note
Requires you to enable the Presence
add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.
this.pubnub.hereNow(
{
channels: ["my_channel"],
channelGroups : ["my_channelGroup"],
includeUUIDs: true,
includeState: true
},
(status, response) => {
console.log(status);
console.log(response);
}
);
Presence
Subscribe to realtime Presence events, such as join
, leave
, and timeout
, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel
:
Note
Requires you to enable the Presence
add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.
this.pubnub.subscribe({
channels: ['my_channel'],
withPresence: true
});
Note
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
History
Retrieve published messages from archival storage:
Note
Requires that the Storage and Playback
add-on is enabled for your key. How do I enable add-on features for my keys? - see https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
this.pubnub.history(
{
channel: 'my_channel',
count: 100, // 100 is the default
stringifiedTimeToken: true // false is the default
},
(status, response) => {
console.log(response);
}
);
Unsubscribe
Stop subscribing (listening) to a channel:
this.pubnub.unsubscribe({
channels : ['my_channel']
});
Note
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.