Use the HealthService API
To develop a Lightning web component with health data features, use the HealthService API to read and write body-weight records on the device.
- Import HealthService into your component definition to make the HealthService API functions available to your code.
- Test to make sure HealthService is available before you call health data functions.
- Use the
getWeight()andwriteWeight()functions to read and write weight records.
In your component’s JavaScript file, import HealthService using the standard JavaScript import statement. Specifically, import the getHealthService() factory function from the lightning/mobileCapabilities module, like so:
After it’s imported into your component, use the factory function to get an instance of HealthService. With your HealthService instance, use the utility functions and constants to verify availability. Then use the health data functions to read and write weight records on the device.
HealthService depends on physical device hardware and platform features. A component that uses HealthService renders without errors on a desktop computer or in a mobile browser, but health data functions fail. To avoid these errors, test if HealthService functionality is available before you use it.
It’s straightforward to read weight history using HealthService.
- Read weight records with
getWeight(), passing aGetWeightOptionsobject to filter by time range and limit the number of records. - Process the results, which are returned as an array of
WeightRecordobjects.
For example:
See getWeight(options) for more details about how to handle weight data and errors.
To save a weight measurement to the device’s health store, construct a valid WeightRecord object and pass it to the writeWeight() function.
- Create a
WeightRecordobject in your JavaScript code with the weight value, unit, and time. This data often comes from a Salesforce record. - Call
writeWeight(), passing theWeightRecordobject. - Handle the result to confirm that the write succeeded, or handle the error.
For example:
See writeWeight(record) for full details about the WeightRecord object structure.
See Also