Connecting to a Session

This page walks through the complete flow for joining an EnableX video session from a React Native app — selecting an audio output device, initialising the room, connecting via the EnxRoom component, and disconnecting cleanly. Follow the steps in order; each depends on the previous one completing successfully.

Connection Flow

Before a user enters a video room from React Native, your app goes through these steps in sequence:

  1. Query available audio output devices — optional but recommended for device picker UIs.
  2. Initialise the room object — call Enx.initRoom() to prepare the SDK.
  3. Render the <EnxRoom> component with the session token — this triggers the connection automatically.
  4. Handle the roomConnected callback to confirm the connection succeeded.
  5. Call Enx.disconnect() when the session ends to cleanly release all resources.
Step 1 — Select Audio Output Device

Before joining, you can query which audio output devices are currently available on the device — speaker, earpiece, Bluetooth headset, or wired headset — and let the user choose one. This step is optional but strongly recommended for any app that includes a device picker in its call UI.

The SDK exposes two methods for this:

Possible device values returned by either method:

// Get all available audio devices
Enx.getDevices((devices) => {
  console.log('Available devices:', devices);
  // devices is an array, e.g. ['SPEAKER_PHONE', 'EARPIECE']
});

// Get the currently active audio device
Enx.getSelectedDevice((device) => {
  console.log('Active device:', device);
});
Step 2 — Initialise the Room

Enx.initRoom() prepares the SDK's internal state and must be called before the EnxRoom component is mounted. It does not return a value — it simply readies the native layer for the upcoming connection.

Call it in componentDidMount for class components, or inside a useEffect with an empty dependency array for functional components. Either way, the goal is the same: run it once, as early as possible, before rendering <EnxRoom>.

// Class component
componentDidMount() {
  Enx.initRoom();
}

// Functional component
useEffect(() => {
  Enx.initRoom();
}, []);
Call Enx.initRoom() exactly once per session, before rendering <EnxRoom>. Calling it multiple times without disconnecting first leads to undefined behaviour — including duplicate event callbacks and media device conflicts.
Step 3 — Join the Room

The <EnxRoom> JSX component is the core of the React Native SDK. When it is mounted (rendered) in your component tree, it automatically connects to the EnableX room using the token you provide. You do not call a separate connect() method — the act of rendering the component is the connection trigger.

This design means your connection lifecycle is tied directly to your React component lifecycle. Mount <EnxRoom> to connect; unmount it (after calling Enx.disconnect()) to leave.

The EnxRoom Component Props

<EnxRoom> accepts the following props:

Prop Type Description
token string The signed JWT from your server for this user and room.
eventHandlers object Object mapping callback names to handler functions.
localInfo object Configuration for the local stream (publishStreamProp).
roomInfo object Reconnection settings.
advanceOptionsInfo object Advanced options such as battery updates and video resolution notifications.

localInfo — Configuring the Local Stream

The localInfo prop is a publishStreamProp object that controls what media the local participant captures and how they appear to others in the room.

const localInfo = {
  audio: true,        // capture microphone
  video: true,        // capture camera
  data: true,         // enable data channel
  name: 'Alice',      // display name shown to others
  audioMuted: false,  // join with mic on
  videoMuted: false   // join with camera on
};

roomInfo — Reconnection Settings

The roomInfo prop configures how the SDK behaves if the network drops mid-session. Setting allow_reconnect: true enables automatic reconnection attempts before the session is considered lost.

const roomInfo = {
  allow_reconnect: true,     // attempt auto-reconnect on disconnect
  number_of_attempts: 3,     // max reconnect attempts
  timeout_interval: 15       // seconds between attempts
};

advanceOptionsInfo — Advanced Options

Use advanceOptionsInfo to enable supplementary SDK features. These are off by default and opt in to additional callbacks your handlers can consume.

const advanceOptionsInfo = {
  battery_updates: true,                // receive battery level events
  notify_video_resolution_change: true  // receive resolution change callbacks
};

Full Example

The example below shows a complete class component that initialises the room, fetches a token, declares all relevant event handlers, and renders <EnxRoom> once the token is available.

import React, { Component } from 'react';
import { Enx, EnxRoom } from 'enx-rtc-react-native';

class VideoSession extends Component {
  constructor(props) {
    super(props);
    this.state = { token: null };
    this.eventHandlers = {
      roomConnected: this.onRoomConnected,
      roomError: this.onRoomError,
      userConnected: this.onUserConnected,
      userDisconnected: this.onUserDisconnected,
      roomDisconnected: this.onRoomDisconnected,
    };
  }

  componentDidMount() {
    Enx.initRoom();
    // Fetch token from your server and set in state
    this.fetchToken().then(token => this.setState({ token }));
  }

  onRoomConnected = (roomData) => {
    console.log('Room connected:', roomData);
  };

  onRoomError = (error) => {
    console.error('Room error:', error.msg, '| Code:', error.result);
  };

  onUserConnected = (user) => {
    console.log('User joined:', user.name);
  };

  onUserDisconnected = (user) => {
    console.log('User left:', user.clientId);
  };

  onRoomDisconnected = (data) => {
    console.log('Disconnected from room');
  };

  render() {
    if (!this.state.token) return null;

    const localInfo = {
      audio: true,
      video: true,
      data: true,
      name: 'Alice'
    };

    const roomInfo = {
      allow_reconnect: true,
      number_of_attempts: 3,
      timeout_interval: 15
    };

    const advanceOptionsInfo = {
      battery_updates: true,
      notify_video_resolution_change: false
    };

    return (
      <EnxRoom
        token={this.state.token}
        eventHandlers={this.eventHandlers}
        localInfo={localInfo}
        roomInfo={roomInfo}
        advanceOptionsInfo={advanceOptionsInfo}
      />
    );
  }
}

export default VideoSession;

Callbacks Received on Connection

When <EnxRoom> mounts and the connection attempt completes, the SDK fires the following callbacks into your eventHandlers object:

Callback When it fires
roomConnected Connection established successfully; room metadata returned.
roomError Connection attempt failed; error code and message returned.
userConnected A new participant joined the room.
activeTalkerList Initial list of active speakers received after joining.
shareStateEvent Current screen sharing state of the room on entry.
canvasStateEvent Current canvas streaming state of the room on entry.
Step 4 — Disconnect

Call Enx.disconnect() to cleanly end the session. This stops all local media capture, closes the WebRTC peer connection, and fires the roomDisconnected callback when the teardown is complete. Only navigate away from the video screen after roomDisconnected has fired.

// Disconnect when the user taps "End Call"
endSession = () => {
  Enx.disconnect();
};

Handle the roomDisconnected callback to know when it is safe to unmount the video screen:

Callback When it fires
roomDisconnected The session has been fully torn down. Safe to navigate away.
Always call Enx.disconnect() before unmounting the video screen component. Failing to do so can leave media devices — camera and microphone — open and in active use by the OS, which will show the recording indicator to the user and may prevent other apps from accessing those devices.
Handling Connection Loss and Reconnection

If the network drops mid-session, the SDK attempts to restore the connection automatically when allow_reconnect: true is set in roomInfo. Rather than immediately tearing down the session, the SDK retries up to number_of_attempts times, waiting timeout_interval seconds between each attempt.

Your app receives a sequence of callbacks during this process, which you can use to show appropriate UI — for example, a "Reconnecting…" overlay during the drop, then restoring the normal call UI on success.

Reconnection Callback Sequence

Callback Meaning
connectionLost Network connection dropped; SDK is attempting to reconnect.
connectedInterrupted Connection was interrupted (brief disruption).
reconnect SDK successfully reconnected the local user.
userReconnect A remote participant reconnected after a drop.
const eventHandlers = {
  connectionLost: () => {
    // Show "Reconnecting..." UI
    this.setState({ status: 'reconnecting' });
  },
  reconnect: (data) => {
    // Hide reconnecting UI, restore call screen
    this.setState({ status: 'connected' });
    console.log('Reconnected:', data);
  },
  userReconnect: (user) => {
    console.log('Remote user reconnected:', user.clientId);
  }
};
Bandwidth and Network Quality Alerts

The SDK monitors network quality in real time throughout the session. When it detects significant changes in available bandwidth — such as a move from a strong Wi-Fi signal to a congested mobile connection — it fires the bandWidthUpdated callback.

Use this event to adapt your UI or warn users about poor connectivity conditions. For example, you might display a low-bandwidth warning badge, automatically disable the video track to preserve audio quality, or log quality data for analytics.

const eventHandlers = {
  bandWidthUpdated: (data) => {
    // data contains bandwidth quality information
    console.log('Bandwidth update:', data);
  }
};