HealthKit bindings for React Native with TypeScript
HealthKit bindings for React Native with TypeScript
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) |
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.
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.
yarn add @kingstinct/react-native-healthkit react-native-nitro-modules{
"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": "Your own custom usage description",
"background": true
}]
]
}
}yarn add @kingstinct/react-native-healthkit react-native-nitro-modulesnpx pod-installNSHealthUpdateUsageDescription and NSHealthShareUsageDescription in your Info.plist 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:
…Some imperative examples:
…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('HKQuantityTypeIdentifierStepCount', {
limit: 2,
})
const nextResult = await queryQuantitySamplesWithAnchor('HKQuantityTypeIdentifierStepCount', {
limit: 2,
anchor: newAnchor,
})
// etc..Workouts (and a few other results, like sources) are returned as proxies: native objects that keep the underlying HKWorkout alive so you can call follow-up functions such as getWorkoutRoutes(), getStatistic() or getAllStatistics() on them. The JavaScript garbage collector frees a proxy, and the HealthKit objects behind it, once it is no longer referenced. The library reports an estimate of each proxy's native size to the JS engine so it can schedule collections sensibly. Note that react-native-nitro-modules currently keeps a small fixed amount of bookkeeping (on the order of a hundred bytes) per native object it has handed to JS for the lifetime of the JS runtime, so memory will not return exactly to baseline even after collection. If you process large numbers of workouts in a loop you can release the HealthKit side eagerly by calling dispose() once you are done with a workout:
const workouts = await queryWorkoutSamples({ limit: 0 })
for (const workout of workouts) {
const routes = await workout.getWorkoutRoutes()
// ... do something with the routes
workout.dispose()
}After dispose() the proxy can no longer be used - calling any function or reading any property on it will throw. If you need to keep the data around, call toJSON() first to get a plain object and store that instead of the proxy:
const plainWorkouts = workouts.map((workout) => {
const json = workout.toJSON()
workout.dispose()
return json
})Other tips for keeping memory in check when working with large datasets:
limit and anchors) instead of fetching everything at once.queryStatisticsForQuantity, queryStatisticsCollectionForQuantity) over fetching every sample when you only need aggregates.toJSON() or the sample queries) in React state rather than proxies.sourceRevision.source on samples and sources on statistics are plain objects, not proxies. To filter queries by a source, get a SourceProxy from querySources() and match it by bundleIdentifier.There are a lot of under-the-hood changes in version 9.0.0, some of them are breaking (although I've tried to reduce it as much as possible).
queryQuantitySamples('HKQuantityTypeIdentifierStepCount') without arguments will simply return the last 20 samples.deleteObjects replaces all previous deletion methods, using the new flexible filters.getWorkoutRoutes.isQuantityCompatibleWithUnit() helper function. Also, units are never required when querying, it always defaults to the users preferred unit.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.
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.
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.
See the contributing guide to learn how to contribute to the repository and the development workflow.
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.
MIT
No open issues yet, or sync has not completed.