React Native Quick Start

Installation

Using npm:

npm install scaledrone-react-native --save

Using Yarn:

yarn add scaledrone-react-native

Connecting

To connect to Scaledrone you need to first create a channel in the admin panel of Scaledrone's website. One instance of Scaledrone establishes a single connection.

const Scaledrone = require('scaledrone-react-native');

const drone = new Scaledrone('CHANNEL_ID_FROM_DASHBOARD');

Listening to messages

Rooms are used to isolate different message types. To listen to messages, you need to subscribe to a specific room.
Users can freely connect to multiple rooms (this does not create extra connections).

const room = drone.subscribe('room_name');

room.on('open', error => {
  if (error) {
    return console.error(error);
  }
  // Connected to room
});

room.on('data', data => {
  // Received a message sent to the room
});

Sending messages

Messages are published to rooms. All users subscribed to the room will receive the message (including the user that sent the message, if they are subscribed). You don't have to be subscribed to a room when publishing to it.

The message can be anything that can be stringified as JSON and then parsed (for example a Number, String or an Object).

const message = {
  hello: 'world',
  score: 10
};

drone.publish({
  room: 'room_name',
  message: message
});

Basic example

Make sure you replace the CHANNEL_ID string with your Scaledrone channel's ID from the dashboard.

Subscribe to messages
Subscribe and publishing messages
const drone = new Scaledrone('CHANNEL_ID');
drone.on('error', error => {
  console.error('Error with connection:', error);
});
drone.on('close', event => {
  console.log('Connection closed:', event);
});

const room = drone.subscribe('my-room');
room.on('data', data => console.log('Received data:', data));
const drone = new Scaledrone('CHANNEL_ID');

drone.on('open', error => {
  if (error) {
    return console.error(error);
  }
  drone.publish({
    room: 'my-room',
    message: {name: 'Bob', score: 42}
  });
});

const room = drone.subscribe('my-room');
room.on('open', error => {
  if (error) {
    console.error(error);
  } else {
    console.log('Connected to room');
  }
});
room.on('data', data => console.log('Received data:', data));

drone.on('error', error => {
  console.error('Error with connection:', error);
});
drone.on('close', event => {
  console.log('Connection closed:', event);
}

Who's online functionality

To keep track of users that are connected to a room see the observable rooms documentation.

Authentication

Socket client authentication is an optional step and can be used to give precise access to specific actions and rooms. Read more about this from the authentication documentation.