### Start Development Packager with bun start Source: https://github.com/kingstinct/react-native-healthkit/blob/master/CONTRIBUTING.md Starts the development packager, which is necessary for running the example app and testing changes during development. This script bundles the project for development. ```sh bun start ``` -------------------------------- ### Start Development Packager Source: https://github.com/kingstinct/react-native-healthkit/blob/master/AGENTS.md Starts the React Native development packager. This command is run from the example application directory to facilitate local development and testing. ```bash cd apps/example && bun start ``` -------------------------------- ### Example: Initial and Incremental Sync of Step Count Samples Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/quantity-samples.md Demonstrates how to perform an initial sync to retrieve all available samples and subsequent incremental syncs to get only changes since the last anchor. This is useful for efficiently updating local data. ```typescript import { queryQuantitySamplesWithAnchor } from '@kingstinct/react-native-healthkit' let anchor: string | undefined // First sync: get all available samples let response = await queryQuantitySamplesWithAnchor( 'HKQuantityTypeIdentifierStepCount', { limit: 100 } ) console.log(`Retrieved ${response.samples.length} samples`) anchor = response.newAnchor // Next sync: only get changes since last anchor response = await queryQuantitySamplesWithAnchor( 'HKQuantityTypeIdentifierStepCount', { limit: 100, anchor } ) console.log(`New samples: ${response.samples.length}`) console.log(`Deleted samples: ${response.deletedSamples.length}`) ``` -------------------------------- ### Install iOS Pods for React Native Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/configuration.md Navigate to the example app's iOS directory and run this command to install the necessary CocoaPods dependencies. This is required before building the iOS project in Xcode. ```bash cd apps/example/ios pod install ``` -------------------------------- ### Example: Get Daily Step Counts Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/quantity-samples.md This example demonstrates how to fetch daily step count totals for the past 30 days. It utilizes `queryStatisticsCollectionForQuantity` with a day interval and logs the results. ```typescript import { queryStatisticsCollectionForQuantity } from '@kingstinct/react-native-healthkit' // Get daily step totals for the last 30 days const dailyStats = await queryStatisticsCollectionForQuantity( 'HKQuantityTypeIdentifierStepCount', ['cumulativeSum'], new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // 30 days ago { day: 1 } ) dailyStats.forEach((stats, index) => { console.log(`Day ${index + 1}: ${stats.sumQuantity?.quantity} steps`) }) ``` -------------------------------- ### Run Example App on iOS with bun run ios Source: https://github.com/kingstinct/react-native-healthkit/blob/master/CONTRIBUTING.md This command builds and runs the example application on an iOS simulator or device. It's used to test your changes in a real-world environment. ```sh bun run ios ``` -------------------------------- ### Installation Source: https://github.com/kingstinct/react-native-healthkit/blob/master/docs/index.html Instructions for installing and configuring the react-native-healthkit library for both Expo and React Native projects. ```APIDOC ## Installation ### Expo 1. **Install the package:** ```bash yarn add @kingstinct/react-native-healthkit ``` 2. **Add the Config Plugin to `app.json`:** ```json { "expo": { "plugins": [ "@kingstinct/react-native-healthkit" ] } } ``` 3. **Build a new Dev Client.** ### React Native 1. **Install the package:** ```bash yarn add @kingstinct/react-native-healthkit ``` 2. **Install CocoaPods:** ```bash npx pod-install ``` 3. **Configure iOS:** * Set `NSHealthUpdateUsageDescription` and `NSHealthShareUsageDescription` in your `Info.plist`. * Enable the HealthKit capability in Xcode. * Add a Swift bridging header if needed (refer to React Native documentation). ``` -------------------------------- ### Install Cocoapods for iOS Source: https://github.com/kingstinct/react-native-healthkit/blob/master/AGENTS.md Installs CocoaPods dependencies for the iOS platform. This is necessary after adding any packages that include native iOS code. Navigate to the example app's iOS directory before running. ```bash cd apps/example/ios && pod install ``` -------------------------------- ### Install React Native HealthKit Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/README.md Install the library and its peer dependency using npm. ```bash npm install @kingstinct/react-native-healthkit react-native-nitro-modules ``` -------------------------------- ### Native/Expo Bare Workflow Installation Source: https://github.com/kingstinct/react-native-healthkit/blob/master/README.md This snippet outlines the installation steps for native React Native projects or Expo's bare workflow. It includes adding the package, installing pods, configuring Info.plist, enabling HealthKit capability in Xcode, and setting up a bridging header for Swift. ```bash yarn add @kingstinct/react-native-healthkit react-native-nitro-modules npx pod-install ``` ```xml NSHealthUpdateUsageDescription Your own custom usage description NSHealthShareUsageDescription Your own custom usage description ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/kingstinct/react-native-healthkit/blob/master/AGENTS.md Installs project dependencies using the Bun package manager. This command should be run at the root level of the project after adding new packages. ```bash bun install ``` -------------------------------- ### Basic Expo Plugin Configuration Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/configuration.md Add this plugin to your app.json for basic setup. It applies default configuration without additional setup. ```json { "expo": { "plugins": ["@kingstinct/react-native-healthkit"] } } ``` -------------------------------- ### Install react-native-healthkit for React Native CLI Source: https://github.com/kingstinct/react-native-healthkit/blob/master/docs/index.html Steps to install the react-native-healthkit library for projects using the React Native CLI. This involves adding the package, installing CocoaPods, and configuring native iOS settings like Info.plist and Xcode capabilities. ```bash yarn add @kingstinct/react-native-healthkit ``` ```bash npx pod-install ``` -------------------------------- ### Example Usage of InterfaceAssertion Source: https://github.com/kingstinct/react-native-healthkit/blob/master/packages/react-native-healthkit/src/types/README-InterfaceVerification.md Demonstrates how to use the `InterfaceAssertion` utility to verify interface synchronization in TypeScript. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Run Codegen and Typecheck Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/configuration.md Run these commands if TypeScript types are missing after updating the library. Ensure you have 'bun' installed and configured. ```bash bun codegen bun typecheck ``` -------------------------------- ### Example: Syncing Category Samples with Anchor Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/category-samples.md Demonstrates how to use `queryCategorySamplesWithAnchor` for both initial data retrieval and subsequent incremental syncs. It shows how to manage the anchor for tracking changes and deletions. ```typescript import { queryCategorySamplesWithAnchor } from '@kingstinct/react-native-healthkit' let anchor: string | undefined // First sync: get initial data let response = await queryCategorySamplesWithAnchor( 'HKCategoryTypeIdentifierMindfulSession', { limit: 50 } ) console.log(`Retrieved ${response.samples.length} mindful sessions`) anchor = response.newAnchor // Subsequent syncs: get only changes response = await queryCategorySamplesWithAnchor( 'HKCategoryTypeIdentifierMindfulSession', { limit: 50, anchor } ) console.log(`New sessions: ${response.samples.length}`) console.log(`Deleted sessions: ${response.deletedSamples.length}`) anchor = response.newAnchor ``` -------------------------------- ### Install react-native-healthkit with Expo Source: https://github.com/kingstinct/react-native-healthkit/blob/master/docs/index.html Instructions for installing the react-native-healthkit library in an Expo project. This includes adding the package via yarn and configuring the Expo app's JSON file to include the healthkit plugin. ```bash yarn add @kingstinct/react-native-healthkit ``` ```json { "expo": { "plugins": [ "@kingstinct/react-native-healthkit" ] } } ``` -------------------------------- ### Example: Save a State of Mind Sample Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/other-data-types.md Demonstrates how to save a 'Momentary' state of mind sample with associated labels and a positive valence. Ensure the 'saveStateOfMindSample' function is imported. ```typescript import { saveStateOfMindSample } from '@kingstinct/react-native-healthkit' const sample = await saveStateOfMindSample( 1, // Momentary ['happy', 'relaxed'], 0.8, // Positive valence ) ``` -------------------------------- ### General Utilities Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/INDEX.md Utility methods for querying sources, deleting objects, and getting preferred units. ```APIDOC ## querySources() ### Description Queries for available data sources. ### Method Not specified (assumed to be a function call within the SDK). ### Endpoint Not applicable. ## currentAppSource() ### Description Gets the current application's data source. ### Method Not specified (assumed to be a function call within the SDK). ### Endpoint Not applicable. ## deleteObjects() ### Description Deletes specified objects. ### Method Not specified (assumed to be a function call within the SDK). ### Endpoint Not applicable. ## getPreferredUnits() ### Description Retrieves the preferred units for measurements. ### Method Not specified (assumed to be a function call within the SDK). ### Endpoint Not applicable. ``` -------------------------------- ### useSources Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/hooks.md Hook to query and reactively get all sources for a specific data type. It returns an array of sources or null while the data is being loaded. ```APIDOC ## `useSources` ### Description Hook to query and reactively get all sources for a specific data type. It returns an array of sources or null while the data is being loaded. ### Method `useSources(identifier: SampleTypeIdentifier): SourceProxy[] | null` ### Parameters #### Path Parameters - **identifier** (`SampleTypeIdentifier`) - Required - The data type to get sources for ### Returns `SourceProxy[] | null` — array of sources or null while loading ### Example ```javascript import { useSources } from '@kingstinct/react-native-healthkit' function SourcesList() { const sources = useSources('HKQuantityTypeIdentifierStepCount') if (sources === null) return Loading... if (!sources.length) return No sources return ( {sources.map(source => ( {source.name} ))} ) } ``` ``` -------------------------------- ### currentAppSource Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/core-module.md Get the source proxy object for the current app. This object contains the app's name and bundle identifier. ```APIDOC ## `currentAppSource` ### Description Get the source proxy object for the current app. This object contains the app's name and bundle identifier. ### Method ```typescript currentAppSource(): SourceProxy ``` ### Returns `SourceProxy` — source object with app's name and bundle identifier ### Example ```typescript import { currentAppSource } from '@kingstinct/react-native-healthkit' const appSource = currentAppSource() console.log(`App name: ${appSource.name}`) console.log(`Bundle ID: ${appSource.bundleIdentifier}`) ``` ``` -------------------------------- ### Query Quantity Samples Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/quantity-samples.md Use this method to retrieve quantity samples like heart rate or steps. Specify the type of quantity, a limit for the number of samples, and optionally a unit, sort order, or filter criteria. The example shows how to fetch the last 10 heart rate samples. ```typescript import { queryQuantitySamples } from '@kingstinct/react-native-healthkit' // Get last 10 heart rate samples in ascending order const samples = await queryQuantitySamples('HKQuantityTypeIdentifierHeartRate', { limit: 10, ascending: true, unit: 'count/min', }) samples.forEach(sample => { console.log(`${sample.quantity} bpm at ${sample.startDate}`) }) ``` -------------------------------- ### Query Sources Hook Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/hooks.md Use this hook to query and reactively get all sources for a specific data type. It returns an array of sources or null while loading. ```typescript useSources(identifier: SampleTypeIdentifier): SourceProxy[] | null ``` ```typescript import { useSources } from '@kingstinct/react-native-healthkit' function SourcesList() { const sources = useSources('HKQuantityTypeIdentifierStepCount') if (sources === null) return Loading... if (!sources.length) return No sources return ( {sources.map(source => ( {source.name} ))} ) } ``` -------------------------------- ### Project Development and Build Commands Source: https://github.com/kingstinct/react-native-healthkit/blob/master/CLAUDE.md Essential CLI commands for managing dependencies, generating Nitro types, and starting the development packager. These commands are critical for maintaining the monorepo structure and ensuring native code compatibility. ```bash # install dependencies bun install # install cocoapods cd apps/example/ios && pod install # generate Nitro types bun codegen # start packager cd apps/example && bun start ``` -------------------------------- ### Error Handling Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/MANIFEST.txt Comprehensive guide to error handling within the library, covering authorization errors, data issues, subscription problems, and debugging techniques. ```APIDOC ## Error Handling This section details strategies for handling errors and potential issues when using the library. ### Authorization Error Handling - Specific guidance on errors related to user permissions. ### Data Availability Issues - How to handle situations where data is not available. ### Subscription Problems - Troubleshooting common issues with data subscriptions. ### Type/Unit Mismatches - Strategies for resolving data type and unit inconsistencies. ### Filter Issues - Debugging problems related to data filtering. ### Sync Strategies - Information on data synchronization. ### Performance Optimization - Tips for optimizing performance. ### Debugging Techniques - General advice and techniques for debugging. ``` -------------------------------- ### Request Authorization Before Querying Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/error-handling.md Always request authorization for HealthKit data types before attempting to query them. This example shows how to request authorization for heart rate data. ```typescript import { requestAuthorization } from '@kingstinct/react-native-healthkit' // Always request authorization before querying await requestAuthorization({ toRead: ['HKQuantityTypeIdentifierHeartRate'], }) // Now safe to query const samples = await queryQuantitySamples('HKQuantityTypeIdentifierHeartRate', { limit: 10, }) ``` -------------------------------- ### Expo Installation Configuration Source: https://github.com/kingstinct/react-native-healthkit/blob/master/README.md This snippet shows how to configure the @kingstinct/react-native-healthkit plugin in your Expo app.json for custom usage descriptions and background modes. It requires a custom Dev Client. ```json { "expo": { "plugins": ["@kingstinct/react-native-healthkit"] } } ``` ```json { "expo": { "plugins": [ ["@kingstinct/react-native-healthkit", { "NSHealthShareUsageDescription": "Your own custom usage description", "NSHealthUpdateUsageDescription": "Your own custom usage description", "background": true }] ] } } ``` -------------------------------- ### Start HealthKit App on Watch Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/workouts.md Initiates the HealthKit app on a paired Apple Watch. This is useful for triggering companion app functionality remotely. The function returns a promise that resolves to a boolean indicating success. ```typescript startWatchApp(): Promise ``` -------------------------------- ### Request Authorization Before Subscribing Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/error-handling.md Ensure authorization is requested before creating subscriptions to prevent the callback from never being invoked. This example shows how to request authorization for heart rate data and then conditionally subscribe. ```typescript import { useSubscribeToChanges } from '@kingstinct/react-native-healthkit' function DataMonitor() { const [authorized, setAuthorized] = useState(false) useEffect(() => { requestAuthorization({ toRead: ['HKQuantityTypeIdentifierHeartRate'], }).then(() => setAuthorized(true)) }, []) // Only subscribe after authorization useSubscribeToChanges( 'HKQuantityTypeIdentifierHeartRate', (args) => { if ('errorMessage' in args) { console.error('Subscription error:', args.errorMessage) } else { console.log('Data updated') } } ) return authorized ? : Requesting access... } ``` -------------------------------- ### Create Changesets for Versioning Source: https://github.com/kingstinct/react-native-healthkit/blob/master/AGENTS.md Creates a changeset for managing package versions and generating changelogs. Follow the prompts to adhere to semantic versioning best practices. ```bash bun changeset ``` -------------------------------- ### Basic HealthKit Usage Pattern Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/README.md Demonstrates checking authorization, querying quantity samples, and using reactive hooks for real-time data. ```typescript import { requestAuthorization, useHealthkitAuthorization, queryQuantitySamples, useMostRecentQuantitySample, } from '@kingstinct/react-native-healthkit' // 1. Check authorization status and request if needed const [authStatus, requestAuth] = useHealthkitAuthorization({ toRead: ['HKQuantityTypeIdentifierHeartRate'], }) // 2. Once authorized, query data const samples = await queryQuantitySamples('HKQuantityTypeIdentifierHeartRate', { limit: 10, }) // 3. Or use hooks for reactive updates function HeartRateDisplay() { const latest = useMostRecentQuantitySample('HKQuantityTypeIdentifierHeartRate') return Heart Rate: {latest?.quantity} bpm } ``` -------------------------------- ### DateFilter Interface Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/types.md Specifies a date range filter for queries, allowing for start and end dates with options for strictness. ```typescript interface DateFilter { readonly startDate?: Date readonly endDate?: Date readonly strictEndDate?: boolean readonly strictStartDate?: boolean } ``` -------------------------------- ### WorkoutEvent Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/types.md Represents an event that occurred during a workout, such as a pause or a change in activity segment, with associated start and end times. ```APIDOC ## WorkoutEvent ### Description An event during a workout like a pause or segment change. ### Fields - **type** (`WorkoutEventType`) - Required - The type of event. - **startDate** (`Date`) - Required - The start date and time of the event. - **endDate** (`Date`) - Required - The end date and time of the event. - **metadata** (`AnyMap`) - Optional - Metadata associated with the event. ``` -------------------------------- ### Query Quantity Samples (React Native) Source: https://github.com/kingstinct/react-native-healthkit/blob/master/README.md Demonstrates how to query quantity samples, such as step counts, from HealthKit. Version 9.0.0 simplifies this by allowing calls without arguments to return the last 20 samples. ```javascript import { queryQuantitySamples } from "@kingstinct/react-native-healthkit"; // Example: Querying step count samples const stepSamples = await queryQuantitySamples('HKQuantityTypeIdentifierStepCount'); // Example: Querying with specific filters (e.g., date range) const startDate = new Date(Date.now() - 24 * 60 * 60 * 1000); const endDate = new Date(); const filteredSamples = await queryQuantitySamples({ quantityType: 'HKQuantityTypeIdentifierStepCount', startDate: startDate.toISOString(), endDate: endDate.toISOString(), limit: 50 // Optional: specify a limit }); ``` -------------------------------- ### queryWorkoutSamplesWithAnchor Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/workouts.md Queries workout samples with support for syncing via anchors, allowing for efficient incremental updates. ```APIDOC ## `queryWorkoutSamplesWithAnchor` ### Description Query workouts with support for syncing via anchors. ### Method `queryWorkoutSamplesWithAnchor` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options.limit** (`number`) - Required - Maximum workouts per query; use -1 or 0 for unlimited * **options.anchor** (`string`) - Optional - Base64-encoded anchor from previous query * **options.filter** (`FilterForWorkouts`) - Optional - Optional filter criteria ### Request Example ```typescript import { queryWorkoutSamplesWithAnchor } from '@kingstinct/react-native-healthkit' let anchor: string | undefined // Initial sync let response = await queryWorkoutSamplesWithAnchor({ limit: 100, }) console.log(`Synced ${response.workouts.length} workouts`) anchor = response.newAnchor // Incremental sync response = await queryWorkoutSamplesWithAnchor({ limit: 100, anchor, }) console.log(`New workouts: ${response.workouts.length}`) console.log(`Deleted: ${response.deletedSamples.length}`) anchor = response.newAnchor ``` ### Response #### Success Response * **workouts** (`readonly WorkoutProxy[]`) - Workouts returned from the query. * **deletedSamples** (`readonly DeletedSample[]`) - Samples that have been deleted. * **newAnchor** (`string`) - The new anchor for subsequent incremental syncs. ``` -------------------------------- ### Get Date of Birth (Synchronous) Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/characteristics.md Retrieves the user's date of birth synchronously. Returns the epoch date if not set. ```typescript import { getDateOfBirth } from '@kingstinct/react-native-healthkit' const dob = getDateOfBirth() const age = new Date().getFullYear() - dob.getFullYear() console.log(`Age: ${age}`) ``` -------------------------------- ### WorkoutEvent Interface Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/types.md Represents an event that occurred during a workout, such as a pause or a segment change. It includes the type of event and its start and end dates. ```typescript interface WorkoutEvent { readonly type: WorkoutEventType readonly startDate: Date readonly endDate: Date readonly metadata?: AnyMap } ``` -------------------------------- ### Save Quantity Sample with Standard Metadata Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/configuration.md Demonstrates how to save a quantity sample (e.g., blood glucose) to HealthKit using standard metadata. Avoid storing sensitive personal health information directly in metadata. ```typescript import { saveQuantitySample } from '@kingstinct/react-native-healthkit' // Good: Standard metadata only await saveQuantitySample( 'HKQuantityTypeIdentifierBloodGlucose', 'mg/dL', 120, now, now, { metadata: { 'HKMetadataKeyFoodType': 'Breakfast', }, } ) ``` -------------------------------- ### Query Workout Samples with Anchor Sync Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/workouts.md Use this function to query workout samples, supporting incremental syncing via anchors. Fetch workouts in batches and retrieve deletions and the next anchor for subsequent syncs. ```typescript queryWorkoutSamplesWithAnchor( options: WorkoutQueryOptionsWithAnchor, ): Promise ``` ```typescript { workouts: readonly WorkoutProxy[], deletedSamples: readonly DeletedSample[], newAnchor: string } ``` ```typescript import { queryWorkoutSamplesWithAnchor } from '@kingstinct/react-native-healthkit' let anchor: string | undefined // Initial sync let response = await queryWorkoutSamplesWithAnchor({ limit: 100, }) console.log(`Synced ${response.workouts.length} workouts`) anchor = response.newAnchor // Incremental sync response = await queryWorkoutSamplesWithAnchor({ limit: 100, anchor, }) console.log(`New workouts: ${response.workouts.length}`) console.log(`Deleted: ${response.deletedSamples.length}`) anchor = response.newAnchor ``` -------------------------------- ### Workouts Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/INDEX.md Functions for querying, saving, and managing workout samples. ```APIDOC ## queryWorkoutSamples(options) ### Description Queries for workout samples within a specified date range. ### Method `queryWorkoutSamples(options)` ### Parameters - **options** (object) - Required - An object containing query parameters. - **startDate** (string) - Required - The start date for the query (ISO 8601 format). - **endDate** (string) - Required - The end date for the query (ISO 8601 format). - **workoutActivityType** (string) - Optional - Filter by specific workout activity type. - **limit** (number) - Optional - The maximum number of samples to return. - **ascending** (boolean) - Optional - Whether to return samples in ascending order (default: false). ### Response #### Success Response (200) - **samples** (array) - An array of workout sample objects. #### Response Example ```json { "samples": [ { "workoutActivityType": "HKWorkoutActivityTypeRunning", "startDate": "2023-10-26T11:00:00.000Z", "endDate": "2023-10-26T11:30:00.000Z", "duration": 1800, "totalDistance": 5000, "totalEnergyBurned": 300 } ] } ``` ``` ```APIDOC ## queryWorkoutSamplesWithAnchor(options) ### Description Queries for workout samples using an anchor date, useful for incremental updates. ### Method `queryWorkoutSamplesWithAnchor(options)` ### Parameters - **options** (object) - Required - An object containing query parameters. - **anchorDate** (string) - Required - The anchor date for the query (ISO 8601 format). - **startDate** (string) - Required - The start date for the query (ISO 8601 format). - **endDate** (string) - Required - The end date for the query (ISO 8601 format). - **workoutActivityType** (string) - Optional - Filter by specific workout activity type. ### Response #### Success Response (200) - **samples** (array) - An array of workout sample objects. #### Response Example ```json { "samples": [ { "workoutActivityType": "HKWorkoutActivityTypeRunning", "startDate": "2023-10-26T11:00:00.000Z", "endDate": "2023-10-26T11:30:00.000Z", "duration": 1800, "totalDistance": 5000, "totalEnergyBurned": 300 } ] } ``` ``` ```APIDOC ## saveWorkoutSample(options) ### Description Saves a new workout sample to HealthKit. ### Method `saveWorkoutSample(options)` ### Parameters - **options** (object) - Required - An object containing the workout sample data. - **workoutActivityType** (string) - Required - The type of workout activity. - **startDate** (string) - Required - The start date of the workout (ISO 8601 format). - **endDate** (string) - Required - The end date of the workout (ISO 8601 format). - **duration** (number) - Optional - The duration of the workout in seconds. - **totalDistance** (number) - Optional - The total distance covered in meters. - **totalEnergyBurned** (number) - Optional - The total energy burned in kilocalories. - **sourceRevision** (object) - Optional - Information about the source revision. ### Response #### Success Response (200) - **sampleID** (string) - The unique identifier of the saved workout sample. #### Response Example ```json { "sampleID": "new-workout-sample-id" } ``` ``` ```APIDOC ## getMostRecentWorkout(options) ### Description Retrieves the most recent workout sample. ### Method `getMostRecentWorkout(options)` ### Parameters - **options** (object) - Required - An object containing query parameters. - **startDate** (string) - Optional - The start date for the search window. - **endDate** (string) - Optional - The end date for the search window. - **workoutActivityType** (string) - Optional - Filter by specific workout activity type. ### Response #### Success Response (200) - **sample** (object) - The most recent workout sample object, or null if none found. #### Response Example ```json { "sample": { "workoutActivityType": "HKWorkoutActivityTypeRunning", "startDate": "2023-10-26T11:00:00.000Z", "endDate": "2023-10-26T11:30:00.000Z", "duration": 1800, "totalDistance": 5000, "totalEnergyBurned": 300 } } ``` ``` ```APIDOC ## startWatchApp(options) ### Description Starts a workout session on a paired Apple Watch. ### Method `startWatchApp(options)` ### Parameters - **options** (object) - Required - An object containing workout details. - **workoutActivityType** (string) - Required - The type of workout activity. - **startDate** (string) - Required - The start date of the workout (ISO 8601 format). - **locationType** (string) - Optional - The location type for the workout. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the watch app was successfully started. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Get Biological Sex (Synchronous) Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/characteristics.md Retrieves the user's biological sex synchronously. Returns one of: `notSet`, `female`, `male`, `other`. ```typescript import { getBiologicalSex, BiologicalSex } from '@kingstinct/react-native-healthkit' const sex = getBiologicalSex() if (sex === BiologicalSex.female) { // Use sex-specific health recommendations } ``` -------------------------------- ### BaseSample Interface Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/types.md Base interface for all health samples. It defines common properties like start and end dates, sample type, and metadata. ```typescript interface BaseSample extends BaseObject { readonly sampleType: SampleType readonly startDate: Date readonly endDate: Date readonly hasUndeterminedDuration: boolean readonly metadata: AnyMap } ``` -------------------------------- ### Type-Safe Quantity Sample Query Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/README.md Shows how to use generic type parameters for strongly-typed quantity sample queries and access type-safe units. ```typescript // Generic function const samples = await queryQuantitySamples<'HKQuantityTypeIdentifierHeartRate'>( 'HKQuantityTypeIdentifierHeartRate', { limit: 10 } ) // Type inference from result const heartRate = samples[0] // QuantitySampleTyped<'HKQuantityTypeIdentifierHeartRate'> const unit = heartRate.unit // 'count/min' (type-safe, not string) ``` -------------------------------- ### Save Correlation Sample Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/other-data-types.md Save a new correlation sample. Requires identifier, samples, start date, and end date. Metadata is optional. ```typescript import { saveCorrelationSample } from '@kingstinct/react-native-healthkit' const now = new Date() const correlationSample = await saveCorrelationSample( 'HKCorrelationTypeIdentifierBloodPressure', [ // Systolic and diastolic samples ], now, now ) ``` -------------------------------- ### getMostRecentCategorySample Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/category-samples.md Retrieves the most recent sample for a specified category type. This is useful for getting the latest recorded data point for a particular health category. ```APIDOC ## `getMostRecentCategorySample` ### Description Get the most recent sample for a category type. ### Method Signature ```typescript getMostRecentCategorySample(identifier: T): Promise | undefined> ``` ### Parameters #### Path Parameters - **identifier** (`CategoryTypeIdentifier`) - Required - The category type to query ### Returns `Promise | undefined>` - the most recent sample or undefined if none exist ### Example ```typescript import { getMostRecentCategorySample } from '@kingstinct/react-native-healthkit' const lastMindfulSession = await getMostRecentCategorySample('HKCategoryTypeIdentifierMindfulSession') if (lastMindfulSession) { const duration = lastMindfulSession.endDate.getTime() - lastMindfulSession.startDate.getTime() console.log(`Last mindful session: ${duration / 1000 / 60} minutes`) } ``` ``` -------------------------------- ### Query Workout Samples Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/workouts.md Retrieves workout samples with options for limiting results, sorting by date, and filtering by activity type, date range, sources, duration, and metadata. Use this to fetch specific workout data based on defined criteria. ```typescript import { queryWorkoutSamples } from '@kingstinct/react-native-healthkit' // Get last 10 running workouts const workouts = await queryWorkoutSamples({ limit: 10, ascending: false, filter: { workoutActivityType: 'HKWorkoutActivityTypeRunning', date: { startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // Last 30 days }, }, }) for (const workout of workouts) { const duration = workout.duration.quantity // In seconds console.log(`${workout.workoutActivityType}: ${duration / 60} minutes`) } ``` -------------------------------- ### Get Wheelchair Use Status (Synchronous) Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/characteristics.md Retrieves the user's wheelchair use status synchronously. The status can be 'notSet', 'notUsingWheelchair', or 'usingWheelchair'. ```typescript import { getWheelchairUse, WheelchairUse } from '@kingstinct/react-native-healthkit' const wheelchairUse = getWheelchairUse() if (wheelchairUse === WheelchairUse.usingWheelchair) { // Adjust activity recommendations or accessibility features } ``` -------------------------------- ### Generate a Changeset with bun run create-changeset Source: https://github.com/kingstinct/react-native-healthkit/blob/master/CONTRIBUTING.md Creates a changeset file, which is used for managing releases, generating changelogs, and triggering NPM publishes. This is a required step for releasing new versions. ```sh bun run create-changeset ``` -------------------------------- ### Get Date of Birth (Asynchronous) Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/characteristics.md Retrieves the user's date of birth asynchronously. This method returns a Promise that resolves to the date of birth. ```typescript getDateOfBirthAsync(): Promise ``` -------------------------------- ### Get Blood Type Asynchronously Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/characteristics.md Retrieves the user's blood type asynchronously. Returns a Promise that resolves to the blood type value. ```typescript getBloodTypeAsync(): Promise ``` -------------------------------- ### Handle No Samples Returned from Query Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/error-handling.md When a query returns an empty array, check the authorization status and consider if the user has recorded data for the requested type. This is common for new applications. ```typescript const samples = await queryQuantitySamples('HKQuantityTypeIdentifierHeartRate', { limit: 10, }) if (samples.length === 0) { // Check authorization status const status = authorizationStatusFor('HKQuantityTypeIdentifierHeartRate') if (status !== AuthorizationStatus.sharingAuthorized) { // Permission issue } else { // No data recorded yet - this is normal for new apps return No heart rate data recorded yet } } ``` -------------------------------- ### Requesting HealthKit Authorization and Fetching Data (TypeScript) Source: https://github.com/kingstinct/react-native-healthkit/blob/master/README.md Demonstrates how to use the `useHealthkitAuthorization` hook to request permissions and then fetch the most recent quantity and category samples. It's crucial to request authorization before attempting to fetch data to prevent app crashes. ```TypeScript import { useHealthkitAuthorization, saveQuantitySample } from '@kingstinct/react-native-healthkit'; const [authorizationStatus, requestAuthorization] = useHealthkitAuthorization(['HKQuantityTypeIdentifierBloodGlucose']) // 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('HKQuantityTypeIdentifierBloodGlucose') const lastBodyFatSample = useMostRecentQuantitySample('HKQuantityTypeIdentifierBodyFatPercentage') const lastMindfulSession = useMostRecentCategorySample('HKCategoryTypeIdentifierMindfulSession') const lastWorkout = useMostRecentWorkout() ``` -------------------------------- ### StateOfMindSample Structure Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/other-data-types.md Defines the structure of a StateOfMindSample object, including its unique identifier, start and end dates, kind, optional labels, valence, and metadata. ```typescript { uuid: string, startDate: Date, endDate: Date, kind: StateOfMindKind, labels?: readonly string[], valence?: number, metadata: AnyMap, } ``` -------------------------------- ### WorkoutProxy Methods Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/INDEX.md Methods for interacting with workout data, including routes and statistics. ```APIDOC ## saveWorkoutRoute() ### Description Saves a workout route. ### Method Not specified (assumed to be a function call within the SDK). ### Endpoint Not applicable. ## getWorkoutRoutes() ### Description Retrieves workout routes. ### Method Not specified (assumed to be a function call within the SDK). ### Endpoint Not applicable. ## getStatistic() ### Description Retrieves a specific statistic for a workout. ### Method Not specified (assumed to be a function call within the SDK). ### Endpoint Not applicable. ## getAllStatistics() ### Description Retrieves all statistics for workouts. ### Method Not specified (assumed to be a function call within the SDK). ### Endpoint Not applicable. ## getWorkoutPlan() ### Description Retrieves the workout plan. ### Method Not specified (assumed to be a function call within the SDK). ### Endpoint Not applicable. ``` -------------------------------- ### Get Most Recent Category Sample Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/category-samples.md Retrieves the latest sample for a specified category type. Use this when you only need the most recent data point for a given category. ```typescript getMostRecentCategorySample( identifier: T, ): Promise | undefined> ``` ```typescript import { getMostRecentCategorySample } from '@kingstinct/react-native-healthkit' const lastMindfulSession = await getMostRecentCategorySample('HKCategoryTypeIdentifierMindfulSession') if (lastMindfulSession) { const duration = lastMindfulSession.endDate.getTime() - lastMindfulSession.startDate.getTime() console.log(`Last mindful session: ${duration / 1000 / 60} minutes`) } ``` -------------------------------- ### Get Biological Sex (Asynchronous) Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/characteristics.md Retrieves the user's biological sex asynchronously. This method returns a Promise that resolves to the biological sex value. ```typescript import { getBiologicalSexAsync, BiologicalSex } from '@kingstinct/react-native-healthkit' const sex = await getBiologicalSexAsync() ``` -------------------------------- ### queryQuantitySamplesWithAnchor Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/quantity-samples.md Queries quantity samples with support for syncing via anchors, which allows tracking changes and deletions since the last query. ```APIDOC ## `queryQuantitySamplesWithAnchor` ### Description Queries quantity samples with support for syncing via anchors (tracking changes and deletions). ### Method `queryQuantitySamplesWithAnchor(identifier: T, options: QueryOptionsWithAnchorAndUnit>): Promise>` ### Parameters #### Path Parameters * `identifier` (QuantityTypeIdentifier) - Required - The quantity type to query. #### Query Parameters * `options.limit` (number) - Required - Maximum samples per query; use -1 or 0 for unlimited. * `options.anchor` (string) - Optional - Base64-encoded anchor from previous query for incremental sync. * `options.unit` (UnitForIdentifier) - Optional - Preferred unit for quantity values. * `options.filter` (FilterForSamples) - Optional - Optional filter criteria. ### Returns `Promise>` - An object containing samples, deleted samples, and the new anchor. ### Response Structure ```typescript { samples: readonly QuantitySampleTyped[], deletedSamples: readonly DeletedSample[], newAnchor: string } ``` ### Example ```typescript import { queryQuantitySamplesWithAnchor } from '@kingstinct/react-native-healthkit' let anchor: string | undefined // First sync: get all available samples let response = await queryQuantitySamplesWithAnchor( 'HKQuantityTypeIdentifierStepCount', { limit: 100 } ) console.log(`Retrieved ${response.samples.length} samples`) anchor = response.newAnchor // Next sync: only get changes since last anchor response = await queryQuantitySamplesWithAnchor( 'HKQuantityTypeIdentifierStepCount', { limit: 100, anchor } ) console.log(`New samples: ${response.samples.length}`) console.log(`Deleted samples: ${response.deletedSamples.length}`) ``` ``` -------------------------------- ### WorkoutSample Interface Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/types.md Defines the structure for a recorded workout session, including activity type, duration, energy, distance, and other metrics. It extends a base sample and includes optional fields for specific workout data. ```typescript interface WorkoutSample extends Omit { readonly workoutActivityType: WorkoutActivityType readonly duration: Quantity readonly totalEnergyBurned?: Quantity readonly totalDistance?: Quantity readonly totalSwimmingStrokeCount?: Quantity readonly totalFlightsClimbed?: Quantity readonly events?: readonly WorkoutEvent[] readonly activities?: readonly WorkoutActivity[] readonly metadata: AnyMap } ``` -------------------------------- ### WorkoutProxy.getWorkoutPlan Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/workouts.md Fetches the workout plan associated with a workout, providing details about the planned activity type and identifier. ```APIDOC ## `getWorkoutPlan` ### Description Get the workout plan associated with this workout. ### Method ```typescript getWorkoutPlan(): Promise ``` ### Returns `Promise` — workout plan or undefined **Plan Structure:** ```typescript { id: string, activityType: WorkoutActivityType, } ``` ``` -------------------------------- ### Get Fitzpatrick Skin Type Asynchronously Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/characteristics.md Retrieves the user's Fitzpatrick skin type asynchronously. Returns a Promise that resolves to the skin type value. ```typescript getFitzpatrickSkinTypeAsync(): Promise ``` -------------------------------- ### Get Fitzpatrick Skin Type Synchronously Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/characteristics.md Retrieves the user's Fitzpatrick skin type synchronously. This is useful for immediate access to skin phototype classification. ```typescript import { getFitzpatrickSkinType, FitzpatrickSkinType } from '@kingstinct/react-native-healthkit' const skinType = getFitzpatrickSkinType() const uvIndexMultiplier = { [FitzpatrickSkinType.I]: 1.25, [FitzpatrickSkinType.II]: 1.0, [FitzpatrickSkinType.III]: 0.85, [FitzpatrickSkinType.IV]: 0.6, [FitzpatrickSkinType.V]: 0.4, [FitzpatrickSkinType.VI]: 0.25, }[skinType] || 1.0 // Use multiplier for sun protection recommendations ``` -------------------------------- ### Linting Code with ESLint Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/configuration.md Execute this command to lint your code, ensuring it adheres to project coding standards and best practices. This helps maintain code quality and consistency. ```bash bun lint ``` -------------------------------- ### Run Unit Tests with bun test Source: https://github.com/kingstinct/react-native-healthkit/blob/master/CONTRIBUTING.md Executes the unit tests for the project using Bun's test runner. This is crucial for ensuring the correctness of individual code components. ```sh bun run test ``` -------------------------------- ### Workout Data Proxy (React Native) Source: https://github.com/kingstinct/react-native-healthkit/blob/master/README.md Shows how workout data is now returned as proxies, which include not only the data but also associated functions. This allows for direct interaction with workout-related functionalities like retrieving routes. ```javascript import { queryWorkoutSamples } from "@kingstinct/react-native-healthkit"; // Example: Fetching workout samples const workouts = await queryWorkoutSamples(); // Example: Accessing workout routes using the proxy function if (workouts && workouts.length > 0) { const firstWorkout = workouts[0]; if (firstWorkout.getWorkoutRoutes) { const routes = await firstWorkout.getWorkoutRoutes(); console.log('Workout Routes:', routes); } } ``` -------------------------------- ### Save Sleep Analysis Category Sample Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/category-samples.md Example of saving a sleep analysis category sample to HealthKit. Ensure the HealthKit module is imported and dates are correctly formatted. ```typescript import { saveCategorySample } from '@kingstinct/react-native-healthkit' const startTime = new Date('2024-06-20T22:00:00') const endTime = new Date('2024-06-21T07:00:00') const saved = await saveCategorySample( 'HKCategoryTypeIdentifierSleepAnalysis', 1, // asleep startTime, endTime ) if (saved) { console.log('Sleep sample saved successfully') } ``` -------------------------------- ### `queryQuantitySamples` Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/api-reference/quantity-samples.md Queries quantity samples with optional filtering and sorting capabilities. ```APIDOC ## `queryQuantitySamples` ### Description Queries quantity samples with optional filtering and sorting. ### Method `queryQuantitySamples(identifier: T, options: QueryOptionsWithSortOrderAndUnit>): Promise[]>` ### Parameters #### Path Parameters - **identifier** (`QuantityTypeIdentifier`) - Required - The quantity type to query (e.g., `'HKQuantityTypeIdentifierHeartRate'`) #### Query Parameters - **options.limit** (`number`) - Required - Maximum number of samples to return; use -1, 0, or negative number for all samples - **options.unit** (`UnitForIdentifier`) - Optional - Preferred unit - **options.ascending** (`boolean`) - Optional - Sort order; true for oldest first, false for newest first - **options.filter** (`FilterForSamples`) - Optional - Optional filter criteria ### Returns `Promise[]>` — array of typed quantity samples ### Request Example ```typescript import { queryQuantitySamples } from '@kingstinct/react-native-healthkit' // Get last 10 heart rate samples in ascending order const samples = await queryQuantitySamples('HKQuantityTypeIdentifierHeartRate', { limit: 10, ascending: true, unit: 'count/min', }) samples.forEach(sample => { console.log(`${sample.quantity} bpm at ${sample.startDate}`) }) ``` ``` -------------------------------- ### Subscribe to Real-Time HealthKit Changes Source: https://github.com/kingstinct/react-native-healthkit/blob/master/_autodocs/README.md Demonstrates subscribing to real-time data changes using a general subscription function and a reactive hook. ```typescript // General subscription const subscription = subscribeToChanges('HKQuantityTypeIdentifierHeartRate', (args) => { if ('errorMessage' in args) { console.error(args.errorMessage) } else { console.log('Heart rate updated') } }) // Or use hooks for automatic cleanup useSubscribeToQuantitySamples('HKQuantityTypeIdentifierHeartRate', (args) => { if ('samples' in args) { args.samples.forEach(sample => { console.log(`${sample.quantity} bpm`) }) } }) ```