> For the complete documentation index, see [llms.txt](https://docs.tryterra.co/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tryterra.co/reference/streaming-api/react-native.md).

# React Native SDK

Every type and function in the React Native RT SDK, with what each platform supports.

The React Native RT SDK wraps the iOS and Android RT SDKs. This page lists its types and functions, and notes where a call works on one platform only.

## Connections

```typescript
export enum Connections {
  ANT = 'ANT',
  BLE = 'BLE',
  WEAR_OS = 'WEAR_OS',
  WATCH_OS = 'WATCH_OS',
  ANDROID = 'ANDROID',
  ALL_DEVICES = 'ALL_DEVICES',
  APPLE = 'APPLE',
}
```

Platform availability:

| Value         | iOS | Android |
| ------------- | --- | ------- |
| `BLE`         | Yes | Yes     |
| `APPLE`       | Yes | No      |
| `WATCH_OS`    | Yes | No      |
| `ANT`         | No  | Yes     |
| `WEAR_OS`     | No  | Yes     |
| `ANDROID`     | No  | Yes     |
| `ALL_DEVICES` | No  | Yes     |

Passing a connection type the current platform does not support fails silently.

## DataTypes

```typescript
export enum DataTypes {
  HEART_RATE = 'HEART_RATE',
  ECG = 'ECG',
  STEPS = 'STEPS',
  HRV = 'HRV',
  CALORIES = 'CALORIES',
  LOCATION = 'LOCATION',
  DISTANCE = 'DISTANCE',
  ACTIVITY = 'ACTIVITY',
  ACCELERATION = 'ACCELERATION',
  GYROSCOPE = 'GYROSCOPE',
  FLOORS_CLIMBED = 'FLOORS_CLIMBED',
  STEPS_CADENCE = 'STEPS_CADENCE',
  SPEED = 'SPEED',
  POWER = 'POWER',
  BIKE_CADENCE = 'BIKE_CADENCE',
  MET = 'MET',
  RR_INTERVAL = 'RR_INTERVAL',
}
```

{% hint style="warning" %}
On iOS, only 12 of these 17 values are recognized: `HEART_RATE`, `ECG`, `STEPS`, `HRV`, `CALORIES`, `LOCATION`, `SPEED`, `DISTANCE`, `STEPS_CADENCE`, `FLOORS_CLIMBED`, `GYROSCOPE`, `ACCELERATION`. The others (`ACTIVITY`, `POWER`, `BIKE_CADENCE`, `MET`, `RR_INTERVAL`) are silently ignored on iOS.
{% endhint %}

## Types

### SuccessMessage

```typescript
export type SuccessMessage = {
  success: Boolean;
  error: String | null;
};
```

### GetUserId

```typescript
export type GetUserId = {
  success: Boolean;
  userId: String | null;
};
```

### Update

Data points delivered through the `"Update"` event emitter.

```typescript
export type Update = {
  ts: String | null;     // ISO 8601 timestamp
  val: number | null;    // Scalar value (e.g. heart rate BPM)
  type: String | null;   // Data type identifier (e.g. "HEART_RATE")
  d: Array<number> | null;  // Array for multi-axis data (e.g. [x, y, z])
};
```

### Device

```typescript
export type Device = {
  id: String | null;
  name: String | null;
  type: String;
};
```

## Initialization

### initTerra

Creates and authenticates the RT SDK instance. Makes a network call.

```typescript
function initTerra(devId: String, referenceId?: String): Promise<SuccessMessage>
```

* `devId` ➡ Your developer ID.
* `referenceId` ➡ Optional user identifier in your system.

### initConnection

Authenticates the SDK user. Makes a network call. Generate the `token` on your backend with [`POST /auth/generateAuthToken`](https://docs.tryterra.co/reference/streaming-api/api-endpoints.md).

```typescript
function initConnection(token: String): Promise<SuccessMessage>
```

### getUserId

Returns the Terra user ID for the device.

```typescript
function getUserId(): Promise<GetUserId>
```

### disconnect

Disconnects from the specified connection type.

```typescript
function disconnect(connections: Connections): Promise<SuccessMessage>
```

## Device scanning

### startDeviceScan

Starts device scanning with the built-in UI widget. Android only. On iOS, this returns `{success: false}` with an error that points you to the [`BLWidget`](#ios-native-view-blwidget) native view.

```typescript
function startDeviceScan(
  connections: Connections,
  useCache: Boolean = false,
  showWidgetIfCacheNotFound: Boolean = false
): Promise<SuccessMessage>
```

### startDeviceScanWithCallback

Starts device scanning and emits each discovered device through the `"Device"` event. Use `connectDevice()` to connect to a chosen device.

```typescript
function startDeviceScanWithCallback(
  connections: Connections
): Promise<SuccessMessage>
```

Listen for devices using `NativeEventEmitter`:

```typescript
import { NativeEventEmitter, NativeModules } from 'react-native';
const deviceEmitter = new NativeEventEmitter(NativeModules.DeviceHandler);
deviceEmitter.addListener('Device', (device: Device) => {
  // Handle discovered device
});
```

### connectDevice

Connects to a specific device discovered by `startDeviceScanWithCallback`.

```typescript
function connectDevice(device: Device): Promise<SuccessMessage>
```

## Data streaming

### startRealtime

Starts real-time data streaming. When you pass a `token`, data goes to Terra's WebSocket server. When `token` is `null`, data streams locally only.

```typescript
function startRealtime(
  connections: Connections,
  dataTypes: Array<DataTypes>,
  token: String | null = null
): Promise<SuccessMessage>
```

Data updates and connection state changes arrive through `NativeEventEmitter`:

```typescript
import { NativeEventEmitter, NativeModules } from 'react-native';

const updateEmitter = new NativeEventEmitter(NativeModules.UpdateHandler);
updateEmitter.addListener('Update', (update: Update) => {
  // Handle data point
});

const connectionEmitter = new NativeEventEmitter(NativeModules.ConnectionHandler);
connectionEmitter.addListener('ConnectionUpdate', (connected: boolean) => {
  // Handle websocket connection state
});
```

### stopRealtime

Stops streaming for the specified connection type.

```typescript
function stopRealtime(connections: Connections): Promise<SuccessMessage>
```

## watchOS integration

### connectWithWatchOS

Establishes a WatchConnectivity session with the paired Apple Watch. iOS only. The promise rejects on Android.

```typescript
function connectWithWatchOS(): Promise<SuccessMessage>
```

## iOS native view: BLWidget

On iOS, the BLE device scanner is a native view component, because iOS does not support the `startDeviceScan` widget flow. Load it with `requireNativeComponent`:

```typescript
import { requireNativeComponent } from 'react-native';
const BLWidget = requireNativeComponent('BLWidget');

// In your JSX:
<BLWidget
  style={{ flex: 1 }}
  withCache={false}
  onSuccessfulConnection={(event) => {
    console.log('Connected:', event.nativeEvent.success);
  }}
/>
```
