import HealthKit from 'react-native-healthkit';import AsyncStorage from '@react-native-async-storage/async-storage';// First query - no anchorlet response = await HealthKit.queryCategorySamplesWithAnchor( 'HKCategoryTypeIdentifierMindfulSession', { limit: -1, // Get all samples });console.log(`Fetched ${response.samples.length} mindful sessions`);// Save the anchor for next timeawait AsyncStorage.setItem('mindfulSessionAnchor', response.newAnchor);// Later query - use stored anchor to get only new dataconst savedAnchor = await AsyncStorage.getItem('mindfulSessionAnchor');if (savedAnchor) { response = await HealthKit.queryCategorySamplesWithAnchor( 'HKCategoryTypeIdentifierMindfulSession', { limit: -1, anchor: savedAnchor, } ); console.log(`New samples: ${response.samples.length}`); console.log(`Deleted samples: ${response.deletedSamples.length}`); // Update the anchor await AsyncStorage.setItem('mindfulSessionAnchor', response.newAnchor);}
The anchor-based query is particularly useful for:
Syncing data efficiently with your backend
Implementing real-time updates in your app
Reducing data transfer by fetching only changes
Always store the newAnchor value and use it in subsequent queries to avoid fetching duplicate data.