javascriptreact-nativehealthkit

Get all health data from react-native-health


I am using react-native-health package to get user's health data from Apple health kit, I can get health data one by one using individual functions, but is there any way to get all health data in a short way?

I am asking for all permissions

const permissions = {
  permissions: {
    read: [
        "ActiveEnergyBurned",
        "BasalEnergyBurned",
        "BloodGlucose",
        "BloodPressureSystolic",
        "BloodPressureDiastolic",
        "BodyFatPercentage",
        "BodyMass",
        "BodyMassIndex",
        "BodyTemperature",
        "DietaryEnergyConsumed",
        "DietaryFatTotal",
        "DietaryProtein",
        "DietaryCarbohydrates",
        "DietarySugar",
        "DietaryFiber",
        "DietaryCalcium",
        "DietaryIron",
        "DietaryPotassium",
        "DietarySodium",
        "DietaryVitaminA",
        "DietaryVitaminC",
        "DietaryVitaminD",
        "DietaryVitaminE",
        "DietaryVitaminK",
        "HeartRate",
        "Height",
        "RestingHeartRate",
        "SleepAnalysis",
        "StepCount",
        "Weight",

    ],
    write: [],
  },
}

and can get different data using different functions like

getEnergyConsumedSamples
getProteinSamples
getFiberSamples
getTotalFatSamples
saveFood
saveWater
getWater
getWaterSamples
getFiberSamples
getInsulinDeliverySamples
saveInsulinDeliverySamples
deleteInsulinDeliverySamples

Solution

  • there is no any function available in react-native-health to get all health data in a single call. it is also obvious because all the different datatype have different data, so it can not give all the data in a single array of different format Object

    you can consider my approach to get related data.

    const METHODS = [
      { id: 1, method: 'getDailyStepCountSamples', name: 'Steps', unit: 'steps' },
      { id: 2, method: 'getSleepSamples', name: 'Sleep', unit: 'sleep' }
    ]
    
     const getHealthData1 = async () => {
    AppleHealthKit.initHealthKit(permissions, async (error) => {
    if (error) {
      console.log('[ERROR] Cannot grant permissions!')
    }
    const options = {
      startDate: new Date(2022, 1, 1).toISOString(),
      endDate: new Date().toISOString(),
    }
    let results = []
    METHODS.forEach(async (item, index, { length }) => {
      await AppleHealthKit[item?.method](
        options,
        (callbackError, res) => {
          if (res) {
            let itemData = {
              "id": item?.id,
              "name": item?.name,
              "value": (res?.value || res[0]?.value || 0).toFixed(), // store any info you want to save according to your use
              "unit": item?.unit
            }
            results.push(itemData);
          }
          if (length === index + 1) {
            console.log("Results All Data:", JSON.stringify(results, null, 2));
          }
        },
      )
    })
    })
    }
    

    Happy Coding :)