React V4React V4Node.jsPhoneGapWebJavaScriptPubNub React V4 SDK 1.2.0

npm install --save pubnub pubnub-react



PubNub React is a wrapper of PubNub JavaScript SDK version 4 that adds a few of extra features to simplify the 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 this will be more suitable for your situation.

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.

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.

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>
        );
    }
}
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 (
            <View>
                {messages.map((m, index) => <Text key={'message' + index}>{m.message}</Text>)}
            </View>
        );
    }
}

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.

 
  • 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 and pn_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);
        });
    }
    

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.

With Javascript SDK V4, you can find three different events (message, presence and status).

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 responsability 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');
    

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);
    

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>
        );
    }

    ...
    

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>
        );
    }

    ...
    

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']);
    

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);
    });
    
In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:

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.

 

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.

 
Set restore as true to allow catch up on the front-end applications.
this.pubnub = new PubNubReact({
    publishKey: 'YOUR PUBLISH KEY',
    subscribeKey: 'YOUR SUBSCRIBE KEY',
    ssl: true 
});
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'] 
});
var existingListener = {
    message: function() {
    } 
}
 
this.pubnub.removeListener(existingListener)
CategoriesDescription
PNNetworkUpCategory
SDK detected that network is online.
PNNetworkDownCategory
SDK detected that network is down.
PNNetworkIssuesCategory
A subscribe event experienced an exception when running.
PNReconnectedCategory
SDK was able to reconnect to pubnub.
PNConnectedCategory
SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
PNAccessDeniedCategory
PAM permission failure.
PNMalformedResponseCategory
JSON parsing crashed.
PNBadRequestCategory
Server rejected the request.
PNDecryptionErrorCategory
If using decryption strategies and the decryption fails.
PNTimeoutCategory
Failure to establish connection due to timeout.
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);
    }
});
this.pubnub.subscribe({
    channels: ['my_channel'],
});
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 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
    }
);
Get occupancy of who's here now on the channel by UUID:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
this.pubnub.hereNow(
    {
        channels: ["my_channel"],
        channelGroups : ["my_channelGroup"],
        includeUUIDs: true,
        includeState: true
    },
    (status, response) => {
        console.log(status);
        console.log(response);
    }
);
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:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
this.pubnub.subscribe({
    channels: ['my_channel'],
    withPresence: true
});
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.
Retrieve published messages from archival storage:
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/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);
    }
);
this.pubnub.unsubscribe({
    channels : ['my_channel']
});
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.