Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,107 @@ if (batch.changesTokenExpired) {
}
```

### React hooks

Typed hooks wrap the imperative API. Each one fetches on mount, fetches again
whenever the app returns to the foreground (built on `pollOnForeground`),
refetches when its arguments change (compared by value, so inline arrays and
objects are fine), and drops results that arrive after unmount or for older
arguments.

```tsx
import {
Permission,
RecordType,
timeRangeLastDays,
timeRangeToday,
useAggregate,
useHealthConnectAvailability,
useHealthConnectPermissions,
useMostRecentRecord,
useReadRecords,
type StepsRecord,
type WeightRecord,
} from '@solutionforest/android-health-connect';

function Dashboard() {
const availability = useHealthConnectAvailability();
const [perms, request] = useHealthConnectPermissions([
Permission.READ_STEPS,
Permission.READ_WEIGHT,
]);
const ready =
availability.value === 'available' && perms.value?.allGranted === true;

// Pass a function for "now"-relative ranges: it is re-evaluated on every
// fetch and does not restart the query on re-render.
const today = useAggregate(RecordType.STEPS, () => timeRangeToday(), {
enabled: ready,
});
const week = useReadRecords<StepsRecord>(RecordType.STEPS, {
timeRangeFilter: () => timeRangeLastDays(7),
enabled: ready,
});
const weight = useMostRecentRecord<WeightRecord>(RecordType.WEIGHT, {
enabled: ready,
});

if (availability.value !== 'available') return <Text>Install Health Connect</Text>;
if (!perms.value?.allGranted) return <Button title="Allow access" onPress={() => void request()} />;
return (
<Text>
{String(today.value?.metrics['COUNT_TOTAL'] ?? '–')} steps today ·{' '}
{week.value?.records.length ?? 0} step records this week ·{' '}
{weight.value ? `${weight.value.weight} kg` : 'no weight'}
</Text>
);
}
```

| Hook | `value` | Notes |
|---|---|---|
| `useHealthConnectAvailability(opts?)` | `'available' \| 'notInstalled' \| 'notSupported'` | Updates after the user installs HC and comes back |
| `useHealthConnectPermissions(perms, opts?)` | `[status, request]`; `status.value` is `{ granted, missing, allGranted }` | `request()` shows the dialog for missing permissions only and resolves with the re-checked result |
| `useReadRecords<T>(type, opts?)` | `ReadRecordsResponse<T>` | Same options as `readRecords`; `timeRangeFilter` may be a function |
| `useMostRecentRecord<T>(type, opts?)` | `T \| null` | Newest record in the window (default: last 30 days) |
| `useAggregate(type, range, opts?)` | `AggregateResult` | `range` may be a function, e.g. `() => timeRangeToday()` |
| `useChanges(token, opts?)` | `PullChangesResult` | Changelog sync; see below |

The data hooks return `{ value, satisfied, loading, error, refresh }`, the same
shape as `useForegroundPoll`, and accept `enabled`, `ready`, `timeoutMs` and
`intervalMs`. Without `ready` each fetch is a single read. Add `ready` to keep
polling through the "0 right after resume" gap:

```ts
const steps = useAggregate(RecordType.STEPS, () => timeRangeToday(), {
ready: (r) => ((r.metrics['COUNT_TOTAL'] as number | null) ?? 0) > 0,
timeoutMs: 20_000,
});
// steps.satisfied === false → timed out; the value may be a real 0.
```

`useChanges(token, { onChanges })` drains the changelog with `pullChanges` on
mount and on every resume. After each pull it continues from
`nextChangesToken`, so persist that token in `onChanges`. Pass `null` to pause
until you have a token. When `value.changesTokenExpired` is true, backfill and
pass a fresh token from `getChangesToken`; a new `token` prop restarts from it.

```tsx
const [token, setToken] = useState<string | null>(storedToken);
useChanges(token, {
onChanges: ({ upsertionChanges, deletionChanges, nextChangesToken, changesTokenExpired }) => {
if (changesTokenExpired) {
void backfill().then(() =>
getChangesToken({ recordTypes: [RecordType.STEPS] }).then(setToken)
);
return;
}
applyToLocalDb(upsertionChanges, deletionChanges);
saveToken(nextChangesToken);
},
});
```

## Supported record types

> The 19 parity-batch types marked below are unit-tested but
Expand Down Expand Up @@ -908,6 +1009,19 @@ if (update.updateAvailable) {
| `readHeartRate(options?)` | … | Convenience helper |
| *(and one per record type, including Mindfulness / SkinTemperature / ActivityIntensity)* | | |

### React hooks

| Hook | Returns | Description |
|---|---|---|
| `useHealthConnectAvailability(opts?)` | `HealthQueryState<HealthConnectAvailability>` | Availability, re-checked on resume |
| `useHealthConnectPermissions(perms, opts?)` | `[HealthQueryState<EnsurePermissionsResult>, request]` | Granted/missing status + request function |
| `useReadRecords<T>(type, opts?)` | `HealthQueryState<ReadRecordsResponse<T>>` | One page of records |
| `useMostRecentRecord<T>(type, opts?)` | `HealthQueryState<T \| null>` | Newest record in the window |
| `useAggregate(type, range, opts?)` | `HealthQueryState<AggregateResult>` | Aggregate metrics for a range |
| `useChanges(token, opts?)` | `HealthQueryState<PullChangesResult>` | Changelog sync that advances its own token |

`HealthQueryState<T>` is `{ value, satisfied, loading, error, refresh }`.

### Features / Matchmaking / PHR

| Function | Returns | Description |
Expand Down
33 changes: 29 additions & 4 deletions docs/api.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,23 @@
<title>API reference — android-health-connect React Native TurboModule</title>
<meta
name="description"
content="API reference for the @solutionforest/android-health-connect TurboModule."
content="API reference for the @solutionforest/android-health-connect TurboModule and its React hooks."
/>
<link rel="canonical" href="https://solutionforest.github.io/AndroidHealthConnect/api.html" />
<meta name="robots" content="index, follow, max-image-preview:large" />
<meta name="theme-color" content="#0a0d0c" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="android-health-connect" />
<meta property="og:title" content="API reference — android-health-connect React Native TurboModule" />
<meta property="og:description" content="API reference for the @solutionforest/android-health-connect TurboModule." />
<meta property="og:description" content="API reference for the @solutionforest/android-health-connect TurboModule and its React hooks." />
<meta property="og:url" content="https://solutionforest.github.io/AndroidHealthConnect/api.html" />
<meta property="og:image" content="https://solutionforest.github.io/AndroidHealthConnect/assets/og-cover.png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="og:image:alt" content="android-health-connect: Health Connect for React Native" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="API reference — android-health-connect React Native TurboModule" />
<meta name="twitter:description" content="API reference for the @solutionforest/android-health-connect TurboModule." />
<meta name="twitter:description" content="API reference for the @solutionforest/android-health-connect TurboModule and its React hooks." />
<meta name="twitter:image" content="https://solutionforest.github.io/AndroidHealthConnect/assets/og-cover.png" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
Expand Down Expand Up @@ -94,6 +94,7 @@ <h4>On this page</h4>
<a href="#availability">Availability</a>
<a href="#permissions">Permissions &amp; helpers</a>
<a href="#records">Records</a>
<a href="#hooks">React hooks</a>
<a href="#features">Features, Matchmaking, PHR</a>
</nav>
</aside>
Expand Down Expand Up @@ -160,8 +161,32 @@ <h2><span class="step">03</span>Records</h2>
</div>
</section>

<section id="hooks">
<h2><span class="step">04</span>React hooks</h2>
<p>
Each hook fetches on mount, on every foreground resume and when its
arguments change, and ignores results after unmount. Data hooks return
<code>HealthQueryState&lt;T&gt;</code>: <code>{ value, satisfied, loading, error, refresh }</code>,
and accept <code>enabled</code>, <code>ready</code>, <code>timeoutMs</code> and
<code>intervalMs</code>. See the <a href="./guides.html#hooks">React hooks guide</a>.
</p>
<div class="table">
<table>
<thead><tr><th>Hook</th><th>Returns</th><th>Description</th></tr></thead>
<tbody>
<tr><td><code>useHealthConnectAvailability(opts?)</code></td><td><code>HealthQueryState&lt;HealthConnectAvailability&gt;</code></td><td>Availability, re-checked on resume</td></tr>
<tr><td><code>useHealthConnectPermissions(perms, opts?)</code></td><td><code>[HealthQueryState&lt;EnsurePermissionsResult&gt;, request]</code></td><td>Granted / missing status, plus <code>request()</code> for the missing ones</td></tr>
<tr><td><code>useReadRecords&lt;T&gt;(type, opts?)</code></td><td><code>HealthQueryState&lt;ReadRecordsResponse&lt;T&gt;&gt;</code></td><td>One page of records; <code>timeRangeFilter</code> may be a function</td></tr>
<tr><td><code>useMostRecentRecord&lt;T&gt;(type, opts?)</code></td><td><code>HealthQueryState&lt;T | null&gt;</code></td><td>Newest record in the window (default: last 30 days)</td></tr>
<tr><td><code>useAggregate(type, range, opts?)</code></td><td><code>HealthQueryState&lt;AggregateResult&gt;</code></td><td>Aggregate metrics; <code>range</code> may be a function</td></tr>
<tr><td><code>useChanges(token, opts?)</code></td><td><code>HealthQueryState&lt;PullChangesResult&gt;</code></td><td>Changelog sync; continues from <code>nextChangesToken</code>, reports via <code>onChanges</code></td></tr>
</tbody>
</table>
</div>
</section>

<section id="features">
<h2><span class="step">04</span>Features, Matchmaking, PHR</h2>
<h2><span class="step">05</span>Features, Matchmaking, PHR</h2>
<p>Check <code>getFeatureStatus</code> before calling any of these.</p>
<div class="table">
<table>
Expand Down
Loading