> ## Documentation Index
> Fetch the complete documentation index at: https://docs.spikeapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# React Native SDK Usage Guide

> Start getting Spike data in 3 steps using Spike SDK for React Native platform.

## Step 1: Create a Spike Connection

To set up the Spike SDK create `SpikeConnectionV3` instance with your Spike application id, application user id and signature unique to each of your application users (more on generating signatures [here](/api-docs/authentication)):

```javascript theme={null}
import Spike from 'react-native-spike-sdk';

const connection = await Spike.createConnectionAPIv3({
    applicationId: 1000,
    signature: "signature",
    endUserId: "user-id"
});
```

## Step 2: Ask User for Permissions

If you plan to use Android Health Connect and/or Apple HealthKit data providers you should first get users permission to use their data:

```javascript theme={null}
// This call may present user with OS native modal asking for read 
// permissions needed to get steps and distance data. If you want to 
// present it only once, you should list all the statistic types you 
// plan to use. Otherwise, you can call this only before you actually 
// want to use the data.
await spikeConnection.requestHealthPermissions({
        statisticTypes: [StatisticsType.steps, StatisticsType.distanceTotal]
      });
```

For Android there are more methods that let you get permissions granted by user, check if Health Connect is installed or should be updated, etc. If you are
OK with Spike SDK handling these, you can use `requestHealthPermissions` only. On iOS `requestHealthPermissions` is the only method that has to be called.
Keep in mind that you should do it before trying to read data from Android Health Connect or Apple HealthKit.

## Step 3: Get Data

<Note>
  The maximum permitted query date range on Android Health Connect is 90 days
</Note>

There are 4 types of data you can retrieve from Spike:

* **Statistics** are calculated values derived from records.
* **Activities** are data about user's activities or workouts.
* **Sleep** is data about user's sleep.
* **Records** consist of the raw data points collected from user devices or applications.

### Statistics

Now you can read hourly statistics data of steps and distance for today:

```javascript theme={null}
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);

const statistics = await spikeConnection.getStatistics(
    [StatisticsType.steps, StatisticsType.distanceTotal],
    start,
    end,
    StatisticsInterval.hour,
    new StatisticsFilter(false, [Provider.apple, Provider.healthConnect])
)
```

where:

```javascript theme={null}
export enum StatisticsType {
  steps = "steps",
  distanceTotal = "distance_total",
  distanceWalking = "distance_walking",
  distanceCycling = "distance_cycling",
  distanceRunning = "distance_running",
  caloriesBurnedTotal = "calories_burned_total",
  caloriesBurnedBasal = "calories_burned_basal",
  caloriesBurnedActive = "calories_burned_active",
  sleepScore = "sleep_score",
  sleepDurationTotal = "sleep_duration_total",
  heartrate = "heartrate",
  heartrateMax = "heartrate_max",
  heartrateMin = "heartrate_min",
  heartrateResting = "heartrate_resting",
  unknown = "_unknown"
}

enum StatisticsInterval {
    day, 
    hour
}

// Filter
class StatisticsFilter {
    excludeManual: boolean = false
    providers: Provider[] | undefined
    activityTags: ActivityTag[] | undefined

    constructor({
        excludeManual = false, 
        providers = undefined,
        activityTags = undefined
    }: StatisticsFilterConstructorParameters) {
        this.excludeManual = excludeManual;
        this.providers = providers;
        this.activityTags = activityTags;
    }
}

// Result:

interface Statistic {
  intervalStart: string;
  intervalEnd: string;
  intervalDuration: number;
  statisticType: StatisticsType;
  statisticValue: number;
  statisticUnit: Unit;
  rowCount: number | null;
  recordIds: UUID[] | null;
}

```

### Records

```javascript theme={null}
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);

const records = await spikeConnection.getRecords({
    ofTypes: metricTypes,
    from: start,
    to: end,
    filter: new StatisticsFilter({
        excludeManual: false,
        providers: [Provider.apple, Provider.healthConnect]
    })
})
```

```javascript theme={null}
enum MetricType {
  heartrateMax = "heartrate_max",
  heartrateMin = "heartrate_min",
  heartrate = "heartrate",
  heartrateResting = "heartrate_resting",
  hrvRmssd = "hrv_rmssd",
  hrvSdnn = "hrv_sdnn",
  elevationMax = "elevation_max",
  elevationMin = "elevation_min",
  elevationGain = "elevation_gain",
  elevationLoss = "elevation_loss",
  ascent = "ascent",
  descent = "descent",
  caloriesBurnedActive = "calories_burned_active",
  caloriesBurnedBasal = "calories_burned_basal",
  caloriesBurned = "calories_burned",
  caloriesIntake = "calories_intake",
  stepsTotal = "steps",
  floorsClimbed = "floors_climbed",
  distanceTotal = "distance",
  distanceWalking = "distance_walking",
  distanceCycling = "distance_cycling",
  distanceRunning = "distance_running",
  distanceWheelchair = "distance_wheelchair",
  distanceSwimming = "distance_swimming",
  speed = "speed",
  speedMax = "speed_max",
  speedMin = "speed_min",
  airTemperatureMax = "air_temperature_max",
  airTemperatureMin = "air_temperature_min",
  spo2 = "spo2",
  spo2Max = "spo2_max",
  spo2Min = "spo2_min",
  longitude = "longitude",
  latitude = "latitude",
  elevation = "elevation",
  durationActive = "duration_active",
  swimmingLengths = "swimming_lenghts",
  swimmingDistancePerStroke = "swimming_distance_per_stroke",
  height = "height",
  weight = "weight",
  birthYear = "birth_year",
  birthDate = "birth_date",
  timezone = "timezone",
  gender = "gender",
  vo2Max = "vo2max",
  bodyTemperature = "body_temperature",
  skinTemperature = "skin_temperature",
  breathingRate = "breathing_rate",
  breathingRateMin = "breathing_rate_min",
  breathingRateMax = "breathing_rate_max",
  bodyFat = "body_fat",
  bodyFatMax = "body_fat_max",
  bodyFatMin = "body_fat_min",
  bodyBoneMass = "body_bone_mass",
  bodyMassIndex = "body_mass_index",
  bloodPressureSystolic = "blood_pressure_systolic",
  bloodPressureSystolicMin = "blood_pressure_systolic_min",
  bloodPressureSystolicMax = "blood_pressure_systolic_max",
  bloodPressureDiastolic = "blood_pressure_diastolic",
  bloodPressureDiastolicMin = "blood_pressure_diastolic_min",
  bloodPressureDiastolicMax = "blood_pressure_diastolic_max",
  unknown = "_unknown"
}

// Result: 

interface SpikeRecord {
  recordId: UUID;
  inputMethod: InputMethod | null;
  startAt: string;
  endAt: string | null;
  modifiedAt: string;
  duration: number | null;
  providerSlug: Provider | null;
  providerSource: ProviderSource | null;
  isSourceAggregated: boolean | null;
  source: RecordSource | null;
  metrics: { [key: string]: number } | null;
  sleepScore: number | null;
  activityTags: ActivityTag[] | null;
  activityType: ActivityType | null;
  sessions: ActivityEntry[] | null;
  laps: ActivityEntry[] | null;
  segments: ActivityEntry[] | null;
  splits: ActivityEntry[] | null;
  samples: ActivityEntry[] | null;
  routePoints: ActivityEntry[] | null;
  sleep: ActivityEntry[] | null;
}
```
