PubNub Setting State Upon Subscribe


Example

When a user subscribes to a channel, you may want to set state for that newly subscribed user. While there is a subscribe with state API, there are some scenarios where this is not the most optimal/reliable technique (like during a disconnect/reconnect situation - the state will be lost and not reinstated).

It is better to explicitly set state once the channel is successfully subscribed. This means you use the subscribe's connect callback to set the state.

var pubnub = PUBNUB({
    publish_key: 'my_pub_key',
    subscribe_key: 'my_sub_key',
    uuid: 'users_uuid'
});

pubnub.subscribe({
    channel: 'channel-1',
    message: function(msg, env, ch){console.log(msg)},
    connect: function(m) {
        console.log('CONNECT: ' + m);
        pubnub.state({
            channel  : 'channel-1', // use the channel param from the subscribe
            state    : {'nickname': 'Bandit', 'mood': 'Pumped!'},
            callback : function(m){console.log(m)},
            error    : function(m){console.log(m)}
        });
    },
    disconnect : function(m){console.log('DISCONNECT: ' + m)},
    reconnect  : function(m){console.log('RECONNECT: ' + m)},
    error      : function(m){console.log('CONNECT: ' + m)}
});