# Basic usage

These steps get a basic StickyHealth integration running in an existing React Native app. For the individual screens, see the **UI components** pages.

## MiriAppProvider

Render `MiriAppProvider` once, near the root of your app. It signs the member in, loads their profile and coach, and makes that state available to every SDK component and to the `useMiriApp` hook below it.

```tsx
import { MiriAppProvider } from '@miri-ai/miri-react-native';

<MiriAppProvider
  apiKey="YOUR_API_KEY"
  scheme="yourappscheme"
  auth={{
    token: idToken,
    provider: 'firebase',
    config: {
      project_id: 'your-firebase-project-id',
    },
  }}
>
  <MainApp />
</MiriAppProvider>
```

### Props

| Prop | Type | Description |
| :--- | :--- | :--- |
| `apiKey` (required) | `string` | The API key we issued to your organization. The provider throws if it is missing. |
| `scheme` (required) | `string` | Your app's URL scheme without the `://` suffix, e.g. `yourappscheme`. |
| `auth` (required) | `MiriAuth` | The member's sign-in token, the provider that issued it, and that provider's config. See below. |
| `theme` | `Theme` | Optional color (`background`, `text`) and font overrides. |
| `privacy` | `{ cover?: boolean }` | `cover` (default `true`) puts an opaque screen over the SDK's own screens while the app is in the background, so the app switcher does not show health data. It does not cover your own screens. |
| `loadingComponent` | `ReactNode` | Shown while the SDK is signing in. |
| `showMessage` | `(type: 'success' \| 'error', message: string, error?: unknown) => void` | Called when an SDK screen wants to show the user a toast, for example after saving settings. |
| `trackEvent` | `(event: EventName, properties?: EventProperties) => void` | Receives SDK analytics events. |
| `onScreenView` | `(screen: string) => void` | Called when an SDK screen is viewed. |
| `logError` | `(message: string, error?: unknown, extra?: Record<string, unknown>) => void` | Receives SDK error logs. |
| `logInfo` | `(message: string, extra?: Record<string, unknown>) => void` | Receives SDK info logs. |
| `logDebug` | `(message: string, extra?: Record<string, unknown>) => void` | Receives SDK debug logs. |
| `userAgentPrefix` | `string` | Prepended to the user agent of the SDK's requests. |

### Signing in: the `auth` prop

`auth` carries a token from your own sign-in system. The SDK exchanges it for a StickyHealth session. It has three fields:

- `token`: the member's ID token, or `null` while nobody is signed in. Changing it to `null` signs the SDK out and clears the data it stored for that member.
- `provider`: `'firebase'`, `'google'`, `'apple'` or `'custom'`.
- `config`: settings for that provider, shown below.

The token's `email`, `name` and `picture` claims, when present, fill in the member's profile.

**Firebase**: if your app uses Firebase Authentication.

```ts
auth={{
  token: idToken, // from user.getIdToken()
  provider: 'firebase',
  config: {
    project_id: 'your-firebase-project-id',
  },
}}
```

`project_id` must be your own Firebase project: it must equal the `aud` claim of the ID token.

**Google**: if your app uses Google Sign-In.

```ts
auth={{
  token: googleIdToken,
  provider: 'google',
  config: {
    client_id: 'your-google-oauth-client-id', // must equal the token's aud claim
    issuer_url: 'https://www.googleapis.com/oauth2/v3/certs', // Google's signing keys
  },
}}
```

**Apple**: if your app uses Sign in with Apple.

```ts
auth={{
  token: appleIdToken,
  provider: 'apple',
  config: {
    team_id: 'your-apple-team-id',
    key_id: 'your-apple-key-id',
    issuer_url: 'https://appleid.apple.com',
  },
}}
```

**Custom**: if your app uses its own sign-in. Your server validates the token; see **Custom token validation**. We register your validation endpoint for your organization, so the app sends no URL.

```ts
auth={{
  token: yourToken,
  provider: 'custom',
  config: {},
}}
```

## useMiriApp

Call `useMiriApp` in any component under `MiriAppProvider` to read the SDK's state.

```ts
const { isLoading, miriUser, activeCoach } = useMiriApp();
```

### Returned values

| Value | Type | Description |
| :--- | :--- | :--- |
| `isLoading` | `boolean` | `true` while the SDK is signing in and loading the member. |
| `miriUser` | `CareSeeker \| null` | The signed-in member, or `null`. |
| `activeCoach` | `Practitioner \| null` | The member's active coach. |
| `selectedDate` | `Date` | The date the tracking components show. |
| `setSelectedDate` | `(date: Date) => void` | Changes `selectedDate`. |
| `getMeals` | `(startDate: Date, endDate?: Date) => Promise<Meal[]>` | Meals logged from the start of `startDate` to the end of `endDate` (or of `startDate` when `endDate` is omitted). |
| `getTrackingItemsProgress` | `() => Promise<{ trackingItemsProgress: TrackingGroup[]; streakCards: Streak[]; medicationProgress: MedicationProgress \| null } \| null>` | Daily progress and streaks for the last seven days. Resolves to `null` if the request fails. |
| `getWeightProgress` | `() => Promise<{ weightGoal: PlanArtifactWeight \| null; weightTracking: WeightTracking \| null }>` | The member's weight goal and weight history. |
| `getBodyComposition` | `() => Promise<BodyComposition \| null>` | The member's latest body composition entry. |
| `getInProgressChatSessionFromModule` | `(moduleName: ModuleNames) => { chatSessionId?: string; moduleName?: string }` | The unfinished chat session for a module, if there is one. |
| `pendingCameraImages` | `CameraImage[]` | Photos captured outside chat that the next `Chat` will load into its input. |
| `setPendingCameraImages` | `(images: CameraImage[]) => void` | Sets `pendingCameraImages` before you navigate to chat. |

## Example

### Pass your sign-in token to the SDK

Get an ID token from your auth provider and keep it in state, for example in your own context:

```tsx
import { createContext, ReactNode, useContext, useState } from 'react';

const AppAuthContext = createContext<{ idToken: string | null }>({ idToken: null });

export const useAppAuth = () => useContext(AppAuthContext);

export const AppAuthProvider = ({ children }: { children: ReactNode }) => {
  const [idToken, setIdToken] = useState<string | null>(null);
  // Sign the user in with your auth provider and call setIdToken(token).
  // Call setIdToken(null) when they sign out.
  return (
    <AppAuthContext.Provider value={{ idToken }}>{children}</AppAuthContext.Provider>
  );
};
```

### App.tsx

```tsx
import { MiriAppProvider } from '@miri-ai/miri-react-native';

export const Root = () => (
  <AppAuthProvider>
    <App />
  </AppAuthProvider>
);

const App = () => {
  const { idToken } = useAppAuth();
  return (
    <MiriAppProvider
      apiKey="YOUR_API_KEY"
      scheme="yourappscheme"
      auth={{
        token: idToken,
        provider: 'firebase',
        config: {
          project_id: 'your-firebase-project-id',
        },
      }}
    >
      <MainApp />
    </MiriAppProvider>
  );
};
```

### MainApp.tsx: show the member's name

```tsx
import { Text } from 'react-native';
import { useMiriApp } from '@miri-ai/miri-react-native';

const MainApp = () => {
  const { isLoading, miriUser } = useMiriApp();
  if (isLoading || !miriUser) {
    return null;
  }
  return <Text>{miriUser.displayName}</Text>;
};
```
