Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@kingstinct/react-native-healthkit

kingstinct17.2kMIT8.4.0TypeScript support: included

React Native bindings for HealthKit

react-native, ios, healthkit, typescript, react-hooks

readme

@kingstinct/react-native-healthkit

Test Status Latest version on NPM Downloads on NPM Discord

React Native bindings for HealthKit with full TypeScript and Promise support covering about any kind of data. Keeping TypeScript mappings as close as possible to HealthKit - both in regards to naming and serialization. This will make it easier to keep this library up-to-date with HealthKit as well as browsing the official documentation (and if something - metadata properties for example - is not typed it will still be accessible).

Data Types Query Save Subscribe Examples
100+ Quantity Types Steps, energy burnt, blood glucose etc..
63 Category Types Sleep analysis, mindful sessions etc..
75+ Workout Activity Types Swimming, running, table tennis etc..
Correlation Types Food and blood pressure
Document Types CDA documents exposed as Base64 data
Clinical Records ⚠️ ⚠️ Lab results etc in FHIR JSON format (see Clinical Records)

Disclaimer

This library is provided as-is without any warranty and is not affiliated with Apple in any way. The data might be incomplete or inaccurate.

Installation

Expo

Usage with Expo is possible - just keep in mind it will not work in Expo Go and you'll need to roll your own Dev Client.

  1. yarn add @kingstinct/react-native-healthkit
  2. Update your app.json with the config plugin:
    {
    "expo": {
     "plugins": ["@kingstinct/react-native-healthkit"]
    }
    }
    this will give you defaults that make the app build without any further configuration. If you want, you can override the defaults:
    {
    "expo": {
     "plugins": [
       ["@kingstinct/react-native-healthkit", {
         "NSHealthShareUsageDescription": "Your own custom usage description",
         "NSHealthUpdateUsageDescription": false,  // if you have no plans to update data, you could skip adding it to your info.plist
         "background": false // if you have no plans to use it in background mode, you could skip adding it to the entitlements
       }]
     ]
    }
    }
  3. Build a new Dev Client

Native or Expo Bare Workflow

  1. yarn add @kingstinct/react-native-healthkit
  2. npx pod-install
  3. Set NSHealthUpdateUsageDescription and NSHealthShareUsageDescription in your Info.plist
  4. Enable the HealthKit capability for the project in Xcode.
  5. Since this package is using Swift you might also need to add a bridging header in your project if you haven't already, you can find more about that in the official React Native docs

Usage

During runtime check and request permissions with requestAuthorization. Failing to request authorization, or requesting a permission you haven't requested yet, will result in the app crashing. This is easy to miss - for example by requesting authorization in the same component where you have a hook trying to fetch data right away.. :)

Some hook examples:

import { HKQuantityTypeIdentifier, useHealthkitAuthorization } from '@kingstinct/react-native-healthkit';

const [authorizationStatus, requestAuthorization] = useHealthkitAuthorization([HKQuantityTypeIdentifier.bloodGlucose])

// make sure that you've requested authorization before requesting data, otherwise your app will crash
import { useMostRecentQuantitySample, HKQuantityTypeIdentifier, useMostRecentCategorySample } from '@kingstinct/react-native-healthkit';

const mostRecentBloodGlucoseSample = useMostRecentQuantitySample(HKQuantityTypeIdentifier.bloodGlucose)
const lastBodyFatSample = useMostRecentQuantitySample(HKQuantityTypeIdentifier.bodyFatPercentage)
const lastMindfulSession = useMostRecentCategorySample(HKCategoryTypeIdentifier.mindfulSession)
const lastWorkout = useMostRecentWorkout()

Some imperative examples:

  import HealthKit, { HKUnit, HKQuantityTypeIdentifier, HKInsulinDeliveryReason, HKCategoryTypeIdentifier } from '@kingstinct/react-native-healthkit';

  const isAvailable = await HealthKit.isHealthDataAvailable();

  /* Read latest sample of any data */
  await HealthKit.requestAuthorization([HKQuantityTypeIdentifier.bodyFatPercentage]); // request read permission for bodyFatPercentage

  const { quantity, unit, startDate, endDate } = await HealthKit.getMostRecentQuantitySample(HKQuantityTypeIdentifier.bodyFatPercentage); // read latest sample

  console.log(quantity) // 17.5
  console.log(unit) // %

  await HealthKit.requestAuthorization([HKQuantityTypeIdentifier.heartRate]); // request read permission for heart rate

  /* Subscribe to data (Make sure to request permissions before subscribing to changes) */
  const [hasRequestedAuthorization, setHasRequestedAuthorization] = useState(false);

  useEffect(() => {
    HealthKit.requestAuthorization([HKQuantityTypeIdentifier.heartRate]).then(() => {
      setHasRequestedAuthorization(true);
    });
  }, []);

  useEffect(() => {
    if (hasRequestedAuthorization) {
      const unsubscribe = HealthKit.subscribeToChanges(HKQuantityTypeIdentifier.heartRate, () => {
        // refetch data as needed
      });
    }

    return () => unsubscribe();
  }, [hasRequestedAuthorization]);

  /* write data */
  await HealthKit.requestAuthorization([], [HKQuantityTypeIdentifier.insulinDelivery]); // request write permission for insulin delivery

  ReactNativeHealthkit.saveQuantitySample(
      HKQuantityTypeIdentifier.insulinDelivery,
      HKUnit.InternationalUnit,
      5.5,
      {
        metadata: {
          // Metadata keys could be arbirtary string to store app-specific data.
          // To use built-in types from https://developer.apple.com/documentation/healthkit/samples/metadata_keys
          // you need to specify string values instead of variable names (by dropping MetadataKey from the name).
          HKInsulinDeliveryReason: HKInsulinDeliveryReason.basal,
        },
      }
    );

HealthKit Anchors (breaking change in 6.0)

In 6.0 you can use HealthKit anchors to get changes and deleted items which is very useful for syncing. This is a breaking change - but a very easy one to handle that TypeScript should help you with. Most queries now return an object containing samples which is what was returned as only an array before.

newAnchor is a base64-encoded string returned from HealthKit that contain sync information. After each successful sync, store the anchor for the next time your anchor query is called to only return the values that have changed.

limit will indicate how many records to consider when sycning data, you can set this value to 0 indicate no limit.

Example:

  const { newAnchor, samples, deletedSamples } = await queryQuantitySamplesWithAnchor(HKQuantityTypeIdentifier.stepCount, {
    limit: 2,
  })

  const nextResult = await queryQuantitySamplesWithAnchor(HKQuantityTypeIdentifier.stepCount, {
    limit: 2,
    anchor: newAnchor,
  })

  // etc..

A note on Apple Documentation

We're striving to do as straight a mapping as possible to the Native Libraries. This means that in most cases the Apple Documentation makes sense. However, when it comes to the Healthkit Metadata Keys the documentation doesn't actually reflect the serialized values. For example HKMetadataKeyExternalUUID in the documentation serializes to HKExternalUUID - which is what we use.

Clinical Records

For accessing Clinical Records use old version (3.x) or use specific branch "including-clinical-records". The reason is we cannot refer to this code natively in apps without getting approval from Apple, this could probably be solved by the config plugin but we haven't had time to look into it yet.

Android alternatives

For a similar library for Android, check out react-native-health-connect that works with the new Health Connect. For Google Fit react-native-google-fit seems to be the most popular option, and and another possible option is to work directly with the Google Fit REST API which I've some experience with.

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

Sponsorship and enterprise-grade support

If you're using @kingstinct/react-native-healthkit to build your production app please consider funding its continued development. It helps us spend more time on keeping this library as good as it can be.

At Kingstinct we're also able to provide enterprise-grade support for this package, find us here or drop an email for more information. Also feel free to join our Discord community.

License

MIT

changelog

8.3.0 (2024-11-29)

Bug Fixes

  • add missing property in tests (532691d)
  • fix infinite calls in useStatisticsForQuantity (2d0b4df)
  • linting error (5a58db6)
  • rename constants (b29c6c7)

Features

  • add queryStatisticsCollectionForQuantity API (#111) (5d70584)
  • add support to HKHealthStore startWatchApp method (d90b298)

8.2.0 (2024-07-31)

Bug Fixes

  • add exports all the way (26b9b0b)
  • continutation edge cases (43b1863)

Features

  • add queryWorkoutSamplesWithAnchor (c991f5d)

8.1.1 (2024-07-04)

Bug Fixes

  • add exports all the way (2bd1813)

8.1.0 (2024-07-04)

Features

  • add queryWorkoutSamplesWithAnchor (edd2f4b)

8.0.1 (2024-06-17)

Bug Fixes

  • building with xcode <16 (3a2bf22)

8.0.0 (2024-06-13)

Features

  • support for iOS 18 types, migrate to bun, bump example-expo to expo 51 with bridgeless mode (e08eecd)
  • support new lux HKUnit for iOS 17 (a546e28) by @jgfino
  • Update native-types.ts with latest activity types (ba15194) by @jstheoriginal

7.3.2 (2023-10-23)

Bug Fixes

  • platform exports gone wrong (95e9a84)

7.3.1 (2023-10-19)

7.3.0 (2023-09-13)

Bug Fixes

  • handle when enddate is nil (1146385)
  • return uuid string (9679e8a)
  • swift placeholder for workoutPlanId (3389e17)

Features

  • add more types (c100a64)
  • allow totals in saveWorkoutSamples (89c57db)
  • create getWorkoutPlanId function (ec3d7ef)
  • handle when function is called by OS less than 17 (81a5e01)
  • move getWorkoutPlan into its own async function (d72d3e5)
  • rename function to getWorkoutPlanById and return id and activity type (edfecf2)
  • rename function to getWorkoutPlanById and return id and activity type (ff252ac)
  • saveWorkoutRoute function (e9eaee8)

7.2.0 (2023-09-04)

Features

7.1.1 (2023-09-02)

Bug Fixes

  • xcode 15 build error for workoutKit logic (16f3d4d)

7.1.0 (2023-09-01)

Bug Fixes

  • handle when enddate is nil (6b675eb)
  • subscribeToObserverQuery not resolving promise (83296e1)

Features

  • add canImport tags so its backwards compatible (87688be)
  • add endDate, uuid and duration to HKWorkoutActivity (d024ce0)
  • update HL types for activity summary (e0fcfdd)
  • update type for HKWorkoutEventType (b168dea)

7.0.6 (2023-08-21)

Bug Fixes

  • remove text-decoration in header (f0d0423)

7.0.5 (2023-08-03)

Bug Fixes

  • nullability on getMostRecent queries (4acb077)

7.0.4 (2023-06-24)

7.0.3 (2023-06-18)

Bug Fixes

  • make config plugin work without specifying props (f7b8bc7)

7.0.2 (2023-06-18)

Bug Fixes

  • deserialization of non-anchor queries (bd8808f)

7.0.1 (2023-06-17)

Bug Fixes

  • don’t modify info.plist when not necessary (672064a)

7.0.0 (2023-05-31)

Features

Maintenance

  • add swiftlint to pre-commit hook
  • remove Android traces - to improve maintainability.

6.1.0 (2023-04-25)

Features

  • exposing HKHeartbeatSeriesQuery for Heartbeat series data (e7c3cb2)

6.0.0 (2023-03-29)

Breaking change and new feature

  • add support for healthkit anchors (55)

5.4.0 (2023-01-03)

Bug Fixes

  • lint: fix few changes caused by default formatter (ebe98a0)

Features

  • hk sources: add func for fetching hk sources (3d534b4)

5.3.0 (2022-12-20)

Bug Fixes

  • lint: use lint to fix warnings (f078fc7)

Features

  • add new method deleteSamples (aad94fa)
  • example: add example for deleteSamples method (64b5f05)

5.2.1 (2022-12-08)

Bug Fixes

  • add more sleep types and fixing VO2Max and UVExposure (207614c)

5.2.0 (2022-11-07)

Bug Fixes

  • clean test run (49c81d7)
  • EventEmitter import (54c03a6)
  • improve readme (326038a)
  • make tests pass, make EAS build workflow not wait (1da9701)

Features

  • adding canAccessProtect data and distance to workoutLocation (b0ce174)

5.1.1 (2022-09-03)

5.1.0 (2022-09-02)

Bug Fixes

  • add eas projectId (ecc067d)
  • add expo-updatesa (a0cea6f)
  • add fonts to native project, fix get workout crash (b3f5875)
  • checkout the PR files as they will look after merge (7a591da)
  • eslint configuration, fix hooks, improving example app (4c93e94)
  • specify working directory (87812b9)
  • use pull_request_target in PR workflow to enable publishing to expo (f1e1972)
  • using more expo-like metro config (68d6bac)
  • workflow fix (58195df)
  • workflow fix (a9dbba2)

Features

  • added delete methods for samples (d48b657)
  • improve example app (c6840b9)
  • improve typings a lot, still trying to get autocompletion with enums/literals just right (178eb27)

4.4.6 (2022-08-19)

4.4.5 (2022-08-19)

4.4.4 (2022-08-19)

4.4.3 (2022-08-19)

4.4.2 (2022-08-19)

4.4.1 (2022-08-19)

4.4.0 (2022-08-18)

Bug Fixes

Features

4.3.0 (2022-06-14)

Features

  • add support for workout locations (f29a3c7)
  • adding support for missing metadata (fe31b31)
  • rename swift to getWorkoutRoutes (636fac6)
  • rename to getWorkoutRoutes (8d384be)
  • updating metadata for routes (6633c37)

Reverts

  • Revert "Add husky, rn-native-hash and dev-client action" (7ebee37)

4.2.0 (2022-05-20)

Bug Fixes

  • fixed mismatched objc method signatures between .m and .swift files (2bae174)
  • lint issues (0cbeb22)
  • updated react-native-paper to version 4.0.0 to fix typescript bindings issue (f00c287)

4.1.1 (2021-06-27)

4.1.0 (2021-03-12)

Bug Fixes

  • badge text and bump packages (f741145)

Features

  • add sourceRevision info to HK samples (36b9bd2)

4.0.1 (2021-03-10)

4.0.0 (2021-01-16)

Bug Fixes

  • removed references to clinical records (49b392a)

3.0.0 (2021-01-01)

Bug Fixes

  • Fix diabetes related methods (f6a320e)
  • note on metadata keys (e9aa91e)

2.0.0 (2020-07-02)

1.0.1 (2020-06-30)

1.0.0 (2020-06-30)

0.3.0 (2020-06-29)

0.2.0 (2020-06-28)

0.1.1 (2020-06-26)

Bug Fixes

  • added requiresMainQueueSetup (7fc1c2c)

Features