0

I am using Apple Health Kit (https://github.com/agencyenterprise/react-native-health) in my React Native app to retrieve Respiratory Rate data to my app. I have a variable called finalVals that I declare before I initialize the health kit, but when I try to populate finalVals with values from the respiratory rate results, the variable stays empty afterward, I presume due to scope issues. https://github.com/agencyenterprise/react-native-health/blob/master/docs/getRespiratoryRateSamples.md This link shows how to use the external function to retrieve the respiratory data

`let finalVals: number[] = [];
      AppleHealthKit.initHealthKit(permissions, (error: string) => {
        if (error) {
          console.log('[ERROR] Cannot grant permissions!');
        }
        //Get the start time of the meditation session
        const newMilli = (durationMinutes * 60 + durationSeconds) * 1000;
        const startDate = new Date(Date.now() - newMilli);
        const options = {
          startDate: new Date(2021, 0, 0).toISOString(),
        };
        AppleHealthKit.getRespiratoryRateSamples(
          options,
          (callbackError: string, results: HealthValue[]) => {
            if (callbackError) {
              return;
            }
            rrVals = Array.from(results.values());

            for (let i = 0; i < rrVals.length; i++) {
              finalVals.push(rrVals[i].value);
            }

            return finalVals;
          },
        );
      });`

After I exit out of the initHealthKit function, finalVals will be empty. However, if I console.log within the function, I can see that the variable is being poulated with the correct values. I understand this has to do with callbacks, and that all my work is being done within the callback parameter, but I can't edit the original initHealthKit function or getRespiratoryRateSamples since it's from an external library. What should I do so that the I can populate my global finalVals from the results variable within getRespiratoryRateSamples?

0 Answers0