> 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/mobile-sdks/react-native-migrating-to-2.md).

# React Native upgrade guide

Move a React Native app from terra-react 1.x to the 2.x wrapper: the package change, old calls mapped to new ones, and the behaviour that changed.

The 2.x React Native wrapper is a rebuild of `terra-react`, not an update. It runs the native [iOS SDK 2.x](https://docs.tryterra.co/mobile-sdks/ios-sdk-2.md) and [Android SDK 2.x](https://docs.tryterra.co/mobile-sdks/android-sdk-2.md) underneath, so it has their behaviour: automatic background sync, a token provider instead of a token argument, and a `connect` that names the end user. Every call changed. Plan it as a migration.

## Replace the package

Remove `terra-react`, including a Samsung-tagged `terra-react` build, and install the 2.x wrapper, `@tryterra/react-native`:

```bash
npm uninstall terra-react
npm install @tryterra/react-native
cd ios && pod install
```

The wrapper needs React Native 0.81 or later, with the New Architecture. It pulls in the native SDKs itself: the `TerraiOS` pod on iOS and `co.tryterra:terra-android` on Android.

Change every import:

{% code title="App.tsx" %}

```typescript
// 1.x
import { initTerra, initConnection, Connections } from 'terra-react';

// 2.x
import { createTerra, EndUser, TerraError } from '@tryterra/react-native';
```

{% endcode %}

## Set up the native side

The wrapper builds its native client when the app launches, before any JavaScript runs, because background delivery needs it then. Your dev ID therefore lives in native configuration, not in JavaScript.

### iOS

1. Update Info.plist and entitlements as the native guide describes: [Update Info.plist and entitlements](https://docs.tryterra.co/pages/pxWMVghOXRxsGOo0WgzI#update-info.plist-and-entitlements). The background task identifier is now `co.tryterra.sdk.refresh`, not `co.tryterra.data.post.request`.
2. Add your dev ID to Info.plist under the `TerraDevID` key.
3. Remove the 1.x `Terra.setUpBackgroundDelivery()` call from your `AppDelegate`, and call the wrapper's bootstrap first thing in `application(_:didFinishLaunchingWithOptions:)`:

{% code title="AppDelegate.swift" %}

```swift
import TerraReactNative

func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
    TerraReactNative.bootstrap()
    // ...the rest of your launch code
    return true
}
```

{% endcode %}

### Android

1. Set `minSdkVersion` to 28 and `compileSdkVersion` to 36.
2. Update the manifest as the native guide describes: [Update the manifest](https://docs.tryterra.co/mobile-sdks/android-migrating-to-2.md#update-the-manifest). The 2.x SDK declares no Health Connect permission for you.
3. Add your dev ID inside `<application>`:

{% code title="AndroidManifest.xml" %}

```xml
<meta-data android:name="co.tryterra.sdk.DEV_ID" android:value="<YOUR_DEV_ID>" />
```

{% endcode %}

Nothing else is needed in code: the wrapper sets itself up before `Application.onCreate`. If your app removed WorkManager's default initializer to configure WorkManager itself, call `TerraReactNative.bootstrap(this)` at the end of `Application.onCreate`.

Without the native setup, every call rejects with `bridge.not_bootstrapped`, and the error's `details.line` names what to add.

## Move `reference_id` to your backend

In 1.x the app passed `referenceId` to `initTerra`. In 2.x your backend sets it when it mints the token. Use the same value 1.x used, so existing users keep their `user_id`:

{% code title="Your backend" %}

```bash
curl --request POST \
  --url 'https://api.tryterra.co/v2/auth/generateAuthToken?reference_id=<YOUR_USER_ID>' \
  --header 'dev-id: <YOUR_DEV_ID>' \
  --header 'x-api-key: <YOUR_API_KEY>'
```

{% endcode %}

The app still names the person, on every connect, with an `EndUser`:

```typescript
EndUser.reference(user.id) // the same value your backend puts in the token
EndUser.anonymous          // only if your backend sends no reference_id
```

The native SDK restores a stored link only for the person it was made for. When someone else signs in on the same phone, it retires the old link and links again, so their data does not arrive under the previous person's `reference_id`. The end user never reaches Terra as identity: Terra trusts only the reference inside the token. See [Name the end user](https://docs.tryterra.co/mobile-sdks/ios-sdk-2.md#name-the-end-user).

## Supply tokens from JavaScript

In 1.x you passed a token to every `initConnection`. In 2.x the native SDK asks for a token only when it has to link: the first time, after a reinstall, for a different end user, or when Terra stopped accepting the device's key. A normal launch restores the link without one.

Create the client once, at module scope, with a token provider that asks your backend:

{% code title="terra.ts" %}

```typescript
import { createTerra } from '@tryterra/react-native';

export const terra = createTerra({
  tokenProvider: () => api.terraToken(), // a fresh token minted by your backend
});
```

{% endcode %}

| Option           | Description                                                                                                                                                                          |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `tokenProvider`  | Returns a promise of a one-time token. Called only while `connect` makes a new link and was given no token. A restored link and a background run never call it                       |
| `tokenTimeoutMs` | How long the native side waits for `tokenProvider`. Defaults to 30 seconds. After that the connect rejects with `bridge.token_timeout` on iOS and `token_provider_failed` on Android |

A token you already hold, for example from a QR code or a deep link, goes straight into the connect: `terra.connect('health', endUser, { token })`. A token passed this way always creates a fresh link.

## Map the calls

| 1.x                                                                          | 2.x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `initTerra(devID, referenceId)`                                              | `createTerra({ tokenProvider })`, once at module scope. The dev ID moves to native configuration ([Set up the native side](#set-up-the-native-side)) and `referenceId` to your backend and the `EndUser` ([Move `reference_id` to your backend](#move-reference_id-to-your-backend)). `terra.attach()` reports the native client: `{ bootstrapped, devId, platform, sdkVersion, backgroundRegistered }`                                                                                                                                                                                                                                                                                              |
| `initConnection(connection, token, schedulerOn, customPermissions)`          | `terra.connect('health', EndUser.reference(user.id))`, then `terra.permissions.request({ read, write, workouts })`. `connect` never shows a permission sheet. Only `permissions.request` does                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `token` argument on `initConnection`                                         | The `tokenProvider` from [Supply tokens from JavaScript](#supply-tokens-from-javascript). Or `terra.connect('health', endUser, { token })` for a token already in hand                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `Connections.APPLE_HEALTH`, `Connections.HEALTH_CONNECT`                     | `'health'`: Apple Health on iOS, Health Connect on Android                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `Connections.SAMSUNG`, or a Samsung-tagged `terra-react`                     | `'health'` reads Samsung Health's data through Health Connect. `'samsungHealth'` reads Samsung Health directly, on Android only. See [Update the Samsung Health setup](#update-the-samsung-health-setup)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `customPermissions: CustomPermissions[]`                                     | `read` in `permissions.request`, from `'activity'`, `'body'`, `'daily'`, `'sleep'` and `'nutrition'`. In 2.2.1 and later, also `'menstruation'`, and `'athlete'` on iOS. In 2.3.0 and later, to ask for single types as `customPermissions` did, use `readTypes`, for example `{ readTypes: ['heartRate', 'steps'] }`. [Permissions](https://docs.tryterra.co/reference/mobile-sdks/permissions-mapping#individual-types) lists the types                                                                                                                                                                                                                                                            |
| `schedulerOn`                                                                | Removed. Background sync is registered natively when the app starts. `terra.background.isRegistered()` answers whether it was                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `checkAuth(connection, devID)`                                               | `terra.diagnostics.state()`, which is `{ state: 'linkRevoked' }` when Terra no longer accepts the device's link                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `getUserId(connection)`                                                      | `terra.connections()`, and `userId` on each connection. `connect` also resolves with the `Connection`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `getDaily`, `getBody`, `getSleep`, `getActivity`, ... with `toWebhook: true` | Removed from the device. [Historical data requests](https://docs.tryterra.co/unified-api/requesting-historical-data.md) from your backend with `to_webhook=true`. The device serves it on its next run                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `getDaily` with `toWebhook: false`                                           | [`terra.daily.steps`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#daily.steps), which takes a range, for example `terra.daily.steps({ kind: 'lastDays', days: 7 })`. In 2.2.1 and later, also [`terra.daily.totals`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#daily.totals) for each day's distance, energy, floors and, on iOS, exercise minutes, [`terra.daily.intraday`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#daily.intraday) for the records under those totals, and [`terra.body.restingHeartRate`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#body.restingheartrate) for resting heart rate |
| `getBody` with `toWebhook: false`                                            | [`terra.body.heartRate`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#body.heartrate). In 2.2.1 and later, also [`terra.body.restingHeartRate`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#body.restingheartrate) and [`terra.body.readings`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#body.readings) for weight, height, body fat, lean mass, HRV, VO2 max, blood pressure, blood glucose, oxygen saturation, temperature and respiratory rate                                                                                                                                                                                 |
| `getSleep` with `toWebhook: false`                                           | [`terra.sleep.segments`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#sleep.segments)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `getActivity` with `toWebhook: false`                                        | [`terra.activity.workouts`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#activity.workouts). In 2.2.1 and later, each `Workout` also carries `title`, and [`terra.activity.routes`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#activity.routes) and [`terra.activity.intensity`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#activity.intensity) return GPS tracks and speed, power and cadence                                                                                                                                                                                                                                    |
| `getNutrition` with `toWebhook: false`                                       | 2.2.1 and later: [`terra.nutrition.quantities`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#nutrition.quantities), one value per nutrient, and [`terra.nutrition.hydration`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#nutrition.hydration) for water. Before 2.2.1 there is no local read: read nutrition from Terra's API or your webhook on your backend                                                                                                                                                                                                                                                                                            |
| `getMenstruation` with `toWebhook: false`                                    | 2.2.1 and later: [`terra.menstruation.flow`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#menstruation.flow) and [`terra.menstruation.events`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#menstruation.events). Request `'menstruation'` first. Before 2.2.1 there is no local read: read it from Terra's API or your webhook                                                                                                                                                                                                                                                                                                                            |
| `getAthlete` with `toWebhook: false`                                         | 2.2.1 and later, iOS only: [`terra.athlete?.profile()`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#athlete.profile). Request `'athlete'` first. `terra.athlete` is `undefined` on Android. Before 2.2.1 there is no local read: read it from Terra's API or your webhook                                                                                                                                                                                                                                                                                                                                                                                                      |
| `postActivity(Connections.APPLE_HEALTH, payload)`                            | `terra.activity.log(entries)`, on iOS and Android. `terra.body.log`, `terra.body.logHeartRate`, `terra.daily.log`, `terra.sleep.log` and `terra.nutrition.log` write the other kinds. Each resolves with the new record IDs, and the namespace's `delete(id)` removes one                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `isHealthConnectAvailable()`                                                 | 2.2.1 and later: [`terra.availability()`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#availability), which needs no connection and resolves with `{ kind: 'available' }` or the reason, such as `{ kind: 'providerAppMissing' }`. Before 2.2.1 there is no separate call: `connect` and `permissions.request` reject with `health_data_unavailable` when Health Connect is missing or needs an update                                                                                                                                                                                                                                                                          |
| `openHealthConnect()`                                                        | No equivalent in 2.x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `grantedPermissions()`                                                       | `terra.permissions.statuses()` on Android, one `PermissionStatus` per category. `terra.permissions.status(category)` for one category on both platforms                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `setIgnoredSources([...])`                                                   | Not available. The SDK uploads data from every app the person granted access to. Merging it with other connections is up to your backend                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| Disconnect through `deauthenticateUser` on your backend                      | Still works. On the device, `terra.disconnect('health')` also forgets the link and revokes its key                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

### Errors

1.x resolved with `{ success, error }`. In 2.x a failed call rejects with a `TerraError`. `TerraError.from(error)` turns anything caught into one:

| Property    | Description                                                                                      |
| ----------- | ------------------------------------------------------------------------------------------------ |
| `code`      | A stable code, for example `token_rejected`, `health_data_unavailable` or `bridge.token_timeout` |
| `retryable` | Whether the same call could succeed if repeated                                                  |
| `message`   | A readable description                                                                           |
| `source`    | The source the error is about, when there is one                                                 |
| `details`   | Extra fields for some codes, such as `line` on `bridge.not_bootstrapped`                         |

### Before and after

{% tabs %}
{% tab title="1.x" %}
{% code title="App.tsx" %}

```typescript
import { Connections, initConnection, initTerra } from 'terra-react';

await initTerra(devID, user.id);
const result = await initConnection(
  Connections.APPLE_HEALTH,
  tokenFromBackend,
  true, // schedulerOn
  [],   // customPermissions
);
if (!result.success) {
  console.error(result.error);
}
```

{% endcode %}
{% endtab %}

{% tab title="2.x" %}
{% code title="App.tsx" %}

```typescript
import { EndUser, TerraError } from '@tryterra/react-native';
import { terra } from './terra'; // the client from terra.ts above

try {
  const connection = await terra.connect('health', EndUser.reference(user.id));
  console.log('Terra user_id', connection.userId);

  await terra.permissions.request({
    read: ['daily', 'sleep', 'activity', 'body'],
  });
} catch (error) {
  const terraError = TerraError.from(error);
  console.error(terraError.code, terraError.message);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Update the Samsung Health setup

In 1.x, Samsung Health came two ways: `Connections.SAMSUNG`, which read Samsung Health's data out of Health Connect, and a Samsung-tagged `terra-react` build, which read Samsung's store directly.

In the 2.x wrapper:

* **Through Health Connect**, connect `'health'`. Samsung Health's data in Health Connect is uploaded with every other app's.
* **Directly**, on Android only, connect `'samsungHealth'`. It needs Samsung's partner approval and Samsung's own `samsung-health-data-api.aar`, which you download from Samsung and add to your app module. Then set `terraSamsungHealth=true` in `android/gradle.properties`. Without that property, `'samsungHealth'` rejects with `health_data_unavailable`. See [Samsung Health](https://docs.tryterra.co/mobile-sdks/samsung-health.md) for approval and what the direct connection reads.

Calls that take a source default to `'health'`. Pass `'samsungHealth'` to reach Samsung Health instead, for example `terra.permissions.request({ read: ['daily'] }, 'samsungHealth')` or `terra.diagnostics.state('samsungHealth')`. Reads, writes and change streams always go to Health Connect.

## Request permissions

`write: ['activity']` asks for workouts and everything a workout can carry: energy and distance. To ask for less, leave `'activity'` out of `write` and pass `workouts` scopes, such as `{ activity: { kind: 'running' }, energy: true, distance: true }`. The [iOS](https://docs.tryterra.co/mobile-sdks/ios-sdk-2.md#request-permissions) and [Android](https://docs.tryterra.co/mobile-sdks/android-sdk-2.md#write-permissions-and-workout-scopes) guides cover the details, including why `permissions.writeStatus('activity')` can be `denied` while a run still logs.

On Android, `permissions.request` resolves with what the sheet granted, `{ read, write, workouts }`, narrowed to what this call asked for. Check it instead of assuming the person said yes. On iOS it resolves with `undefined`, because HealthKit does not tell an app whether a read was allowed.

When the request asks to read anything, the Android sheet also asks for background read and history read, if your manifest declares them. Check them afterwards with `terra.permissions.backgroundReadStatus()` and `terra.permissions.historyReadStatus()`. Both are Android only, and `undefined` on iOS.

The wrapper registers the Android permission sheet with each of your activities as it is created, so there is no launcher to set up. Two Android-only rejections are new in the wrapper. Both are retryable:

| Code                                  | Cause                                                                                           |
| ------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `bridge.no_activity`                  | No activity is on screen to present the sheet, for example because the app is in the background |
| `bridge.permission_sheet_unavailable` | A sheet from an earlier request is still up, or the activity's sheet was released               |

## Behaviour that changed

* **Sync is automatic.** The SDK uploads after a permission request grants something new, after a new link, when the app comes to the foreground, and on background runs. There is no call that starts a sync.
* **The first sync reaches two years back**, then only what changed. See the [iOS](https://docs.tryterra.co/mobile-sdks/ios-sdk-2.md) and [Android](https://docs.tryterra.co/mobile-sdks/android-sdk-2.md) guides for what syncs and when.
* **A link is restored without a network call.** `terra.connect('health', endUser)` for the same end user on a normal launch costs nothing and works offline.
* **Diagnostics.** `terra.diagnostics.state()`, `terra.diagnostics.lastDelivery()` and `terra.diagnostics.events(listener)` replace guessing from `checkAuth`. `terra.diagnostics.report()` returns a redacted support report that never contains a health value.

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}
