Graph react native SDK

Overview

Some data providers don't provide data through a web API, and restrict data access to on-device apps.

See Integrations for a full list of SDK-based integrations.

This means that users cannot agree to share through the widget. Instead, the user has to agree to share data for e.g. Apple Health or Samsung Health on their device directly.

This requires your product to call the corresponding on-device SDK for the data provider (e.g. calling Apple Health and ask for data sharing).

This SDK allows you to use Graph API for your SDK users just as the rest of the providers.


Usage

To use the SDK you will have to complete initConnection on the device and retrieve the UserID by using the terra-react library. Please refer to the following link on how to set that up: https://docs.tryterra.co/reference/backend-clients-reference-1

After setting up the connection, you can get the UserID by using getUserId(). You can then user the userID to generate a token and generate a graph by passing the token.

Installation

npm -i react-native-terra-react-graphs

Example usage

import * as React from 'react';
import { useEffect, useState } from 'react';

import { ActivityIndicator, StyleSheet, View } from 'react-native';
import { Connections, getUserId, initConnection, initTerra } from 'terra-react';
import { TerraGraph } from 'react-native-terra-react-graphs';
import { GraphType, TimePeriod } from '../../src/type';
import { Config } from './Config';

async function inits(
  SDKToken: string,
  devID: string,
  refID: string,
  connection: Connections,
  schedulerOn: boolean,
  setUserId: React.Dispatch<React.SetStateAction<String | null>>
) {
  let initT = await initTerra(devID, refID);
  console.log('initTerra: ' + initT.success);
  let initC = await initConnection(connection, SDKToken, schedulerOn);
  console.log('initConnection: ' + initC.success);
  if (initC.success) {
    let initUseId = await getUserId(connection);
    const user_id = initUseId.userId;
    setUserId(user_id);
    console.log('initUseId: ' + initUseId.userId);
  }
}
export default function App() {
  const [userId, setUserId] = useState<String | null>(null);
  const [graphToken, setGraphToken] = useState('');
	// Funtion to complete authentication and get the userId
  const getSDKTokenAndUserId = async () => {
    try {
      // Make this request in the backend instead. This is only for demo purposes.
      const url = `https://api.tryterra.co/v2/auth/generateAuthToken`;
      const headers = {
        'dev-id': Config.DevID,
        'x-api-key': Config.APIKEY,
      };
      const response = await fetch(url, {
        method: 'POST',
        headers: headers,
      });
      const SDKJson = await response.json();
      await inits(
        SDKJson.token,
        Config.DevID,
        '1',
        Connections.APPLE_HEALTH,
        true,
        setUserId
      );
    } catch (error) {
      console.error(error);
    }
  };
	// Funtion to get the getGraphToken of the UserID
  const getGraphToken = async () => {
    try {
      // Make this request in the backend instead. This is only for demo purposes.
      const url = `https://api.tryterra.co/v2/graphs/token?user_id=${userId}`;
      const headers = {
        'dev-id': Config.DevID,
        'x-api-key': Config.APIKEY,
      };
      const responseGraphToken = await fetch(url, {
        method: 'GET',
        headers: headers,
      });
      const GraphJson = await responseGraphToken.json();
      setGraphToken(GraphJson.token);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    // Access the updated userId here
    if (userId !== null) {
      getGraphToken();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [userId]);

  useEffect(() => {
    setUserId('');
    setGraphToken('');
    getSDKTokenAndUserId();
  }, []);

  const start = '2023-06-08';
  const end = '2023-06-09';
  return (
    <View style={styles.container}>
      <View style={styles.box}>
        <TerraGraph
          type={GraphType.DAILY_RHR_SUMMARY}
          styles={{ flex: 1, justifyContent: 'center' }}
          loadingComponent={<ActivityIndicator />}
          startDate={start}
          endDate={end}
          token={graphToken}
          timePeriod={TimePeriod.WEEK}
          toWebhook={false}
          connections={Connections.APPLE_HEALTH}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    top: '5%',
  },
  box: {
    height: '40%',
  },
});

Graph Type Enum

enum GraphType {
  ACTIVITY_HR_SAMPLES = 'ACTIVITY_HR_SAMPLES',
  ACTIVITY_POWER_SAMPLES = 'ACTIVITY_POWER_SAMPLES',
  BODY_GLUCOSE_SUMMARY = 'BODY_GLUCOSE_SUMMARY',
  BODY_GLUCOSE_AGP = 'BODY_GLUCOSE_AGP',
  DAILY_STEPS_SUMMARY = 'DAILY_STEPS_SUMMARY',
  DAILY_RHR_SUMMARY = 'DAILY_RHR_SUMMARY',
  SLEEP_HR_SUMMARY = 'SLEEP_HR_SUMMARY',
  SLEEP_HRV_SUMMARY = 'SLEEP_HRV_SUMMARY',
  SLEEP_ASLEEP_SUMMARY = 'SLEEP_ASLEEP_SUMMARY',
  SLEEP_RHR_SUMMARY = 'SLEEP_RHR_SUMMARY',
  SLEEP_RESPIRATORY_RATE_SUMMARY = 'SLEEP_RESPIRATORY_RATE_SUMMARY',
  SLEEP_REM_SUMMARY = 'SLEEP_REM_SUMMARY',
  SLEEP_LIGHT_SUMMARY = 'SLEEP_LIGHT_SUMMARY',
  SLEEP_DEEP_SUMMARY = 'SLEEP_DEEP_SUMMARY',
  SLEEP_REM_LIGHT_DEEP_PIE_SUMMARY = 'SLEEP_REM_LIGHT_DEEP_PIE_SUMMARY',
}

Time period Enum

enum TimePeriod {
  DAY = 'DAY',
  WEEK = 'WEEK',
  TWO_WEEKS = 'TWO_WEEKS',
  MONTH = 'MONTH',
  THREE_MONTHS = 'THREE_MONTHS',
  HALF_YEAR = 'HALF_YEAR',
  YEAR = 'YEAR',
}

Component Properties

type GraphPropsType = {
  type: GraphType;
  token: string;
  styles?: ViewStyle;
  loadingComponent?: JSX.Element;
  test?: boolean;
  startDate?: string;
  endDate?: string;
  timePeriod?: TimePeriod;
  getImg?: boolean;
  imgWidth?: bigint;
  imgHeight?: bigint;
  getSmallTemplate?: boolean;
  toWebhook: boolean;
  connections: Connections;
};

Component Properties

PropertyTypeDescription
typeGraph Type EnumThe graph type desired. See valid types on https://docs.tryterra.co/reference/using-graphs#graph-types
tokenstringAn access token for a particular user to enable data access and graph rendering. Generate a token using https://docs.tryterra.co/reference/generate-token
stylesViewStyleCustom css properties for the graph container
loadingComponentJSX.ElementCustom element displayed when the graph is loading. Default is null
testbooleanWhether to use a test graph. Test graphs don't require a valid token as they are intended to test the UI / UX
startDatestring (ISO 8601)(optional) If start_date is not specified, the data will be spanned across the last week, two weeks, or month (respectively) from today. If start_date is specified, the data will be spanned across the week following the specified start date. (e.g. 2023-02-03)
endDatestring (ISO 8601)Customize the time period more by specifying an exact end date for the graph. This param overrides the timepeirod.
timePeriodTime period EnumIf start_date is not specified, the data will be spanned across the last week, two weeks, or month (respectively) from today. If start_date is specified, the data will be spanned across the week following the specified start date. For time period more than three months, the data will be spanned across a longer range of time with lower sample points.
getImgbooleanSet this parameter to True to get an png image of the graph instead of a frontend html.
imgWidthintSet return image width
imgHeightintSet return image height
getSmallTemplatebooleanWether to use a small widget template.
toWebhookbooleanWether to send the data to your webhook
connectionsconnections enumSDK Terra-React connection enum e.g Connections.APPLE_HEALTH