### Track App Installations and First Open with React Native Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt This snippet demonstrates how to track app installation events with channel attribution and track the first app open in React Native using the SensorsAnalytics SDK. It includes examples for the new `trackAppInstall` method and the deprecated `trackInstallation` method, along with tracking the initial user session. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Track app install with channel attribution (new method) SensorsAnalytics.trackAppInstall({ channel: 'google_play', campaign: 'summer_sale_2024', ad_network: 'google_ads', ad_campaign_id: 'GG_12345', referrer: 'facebook_ad', install_source: 'organic', install_date: '2024-06-15' }); // Legacy method (deprecated, use trackAppInstall instead) SensorsAnalytics.trackInstallation('AppInstall', { channel: 'app_store', source: 'search', medium: 'organic' }); // Track first open after install SensorsAnalytics.track('FirstAppOpen', { time_since_install_hours: 0.5, os_version: '17.2', device_model: 'iPhone 14 Pro' }); ``` -------------------------------- ### App Installation Tracking Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Track app installation events with channel attribution for marketing campaign effectiveness analysis. This includes tracking new installs and first opens. ```APIDOC ## App Installation Tracking ### Description Track app installation events with channel attribution for marketing campaign effectiveness analysis. This includes tracking new installs and first opens. ### Methods - `trackAppInstall(properties)`: Tracks an app installation event with detailed attribution properties. - `trackInstallation(eventName, properties)`: Legacy method for tracking installation events (deprecated). - `track(eventName, properties)`: Used to track subsequent events like 'FirstAppOpen'. ### Parameters #### `trackAppInstall` Method Parameters - **properties** (object) - Required - An object containing installation attribution details. Common fields include: - `channel` (string) - Required - The source channel of the install (e.g., 'google_play', 'app_store'). - `campaign` (string) - Optional - The marketing campaign name. - `ad_network` (string) - Optional - The ad network used. - `ad_campaign_id` (string) - Optional - The specific ad campaign ID. - `referrer` (string) - Optional - The referrer information. - `install_source` (string) - Optional - The source of the install (e.g., 'organic', 'paid'). - `install_date` (string) - Optional - The date of installation (YYYY-MM-DD). #### `trackInstallation` Method Parameters (Legacy/Deprecated) - **eventName** (string) - Required - Typically 'AppInstall'. - **properties** (object) - Required - An object containing installation properties (e.g., `channel`, `source`, `medium`). #### `track` Method Parameters (for 'FirstAppOpen') - **eventName** (string) - Required - The name of the event, e.g., 'FirstAppOpen'. - **properties** (object) - Required - An object containing event-specific details like `time_since_install_hours`, `os_version`, `device_model`. ### Request Example (trackAppInstall) ```javascript SensorsAnalytics.trackAppInstall({ channel: 'google_play', campaign: 'summer_sale_2024', ad_network: 'google_ads', ad_campaign_id: 'GG_12345', referrer: 'facebook_ad', install_source: 'organic', install_date: '2024-06-15' }); ``` ### Request Example (FirstAppOpen) ```javascript SensorsAnalytics.track('FirstAppOpen', { time_since_install_hours: 0.5, os_version: '17.2', device_model: 'iPhone 14 Pro' }); ``` ### Response These methods trigger an event tracking the app installation or first open, and do not return a value. ``` -------------------------------- ### Track Screen Views with Sensors Analytics SDK Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Track page or screen views with custom properties using the Sensors Analytics SDK. This helps understand user navigation patterns and popular content. Examples include tracking a product details screen and an article screen, including engagement data like time spent. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; import { useEffect } from 'react'; // Track screen view in navigation function ProductDetailsScreen({ route }) { const { productId } = route.params; useEffect(() => { SensorsAnalytics.trackViewScreen('ProductDetailsScreen', { product_id: productId, product_category: 'Electronics', referrer_screen: 'HomeScreen', is_deeplink: false }); }, [productId]); return ( // Screen content ); } // Track screen with user engagement data function ArticleScreen({ article }) { useEffect(() => { const startTime = Date.now(); SensorsAnalytics.trackViewScreen('ArticleScreen', { article_id: article.id, article_title: article.title, author: article.author, category: article.category, word_count: article.wordCount, estimated_read_time: article.readTime }); return () => { const timeSpent = Math.floor((Date.now() - startTime) / 1000); SensorsAnalytics.track('ArticleViewed', { article_id: article.id, time_spent_seconds: timeSpent, scroll_depth: getScrollDepth() }); }; }, [article]); } // Placeholder for getScrollDepth function function getScrollDepth() { // Implementation to get scroll depth return 0.75; // Example value } ``` -------------------------------- ### Timed Event Tracking Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Measures event duration by starting a timer, performing actions, and ending the timer with the elapsed time automatically calculated. ```APIDOC ## Timed Event Tracking ### Description Measures event duration by starting a timer, performing actions, and ending the timer with the elapsed time automatically calculated. ### Method `SensorsAnalytics.trackTimerStart(eventName)` `SensorsAnalytics.trackTimerPause(eventName)` `SensorsAnalytics.trackTimerResume(eventName)` `SensorsAnalytics.trackTimerEnd(eventName, properties)` `SensorsAnalytics.clearTrackTimer()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **eventName** (string) - Required - The name of the timed event. - **properties** (object) - Optional - An object containing key-value pairs representing event properties for the end event. ### Request Example ```javascript // Start timer for video playback SensorsAnalytics.trackTimerStart('VideoWatched'); // User watches video... // Pause the timer when video is paused SensorsAnalytics.trackTimerPause('VideoWatched'); // Resume timer when playback continues SensorsAnalytics.trackTimerResume('VideoWatched'); // End timer and send event with duration SensorsAnalytics.trackTimerEnd('VideoWatched', { video_id: 'V12345', video_title: 'Product Demo', video_duration: 300, completion_rate: 0.85, quality: '1080p' }); // Clear all active timers SensorsAnalytics.clearTrackTimer(); ``` ### Response No specific response structure is defined for timed event tracking. Success is indicated by the absence of errors. ``` -------------------------------- ### Measure Event Duration with Timed Events (JavaScript) Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Measures the duration of user interactions by starting, pausing, resuming, and ending timers associated with specific events. The SDK automatically calculates the elapsed time and sends it as part of the event data when the timer is ended. It also supports clearing all active timers. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Start timer for video playback SensorsAnalytics.trackTimerStart('VideoWatched'); // User watches video... // Pause the timer when video is paused SensorsAnalytics.trackTimerPause('VideoWatched'); // Resume timer when playback continues SensorsAnalytics.trackTimerResume('VideoWatched'); // End timer and send event with duration SensorsAnalytics.trackTimerEnd('VideoWatched', { video_id: 'V12345', video_title: 'Product Demo', video_duration: 300, completion_rate: 0.85, quality: '1080p' }); // Clear all active timers SensorsAnalytics.clearTrackTimer(); ``` -------------------------------- ### Register and Manage Super Properties with Sensors Analytics SDK Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Register properties that automatically attach to all tracked events using the Sensors Analytics SDK. This reduces redundant code and ensures consistency. It includes registering, retrieving, unregistering, and clearing super properties, as well as getting system-generated preset properties. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Register super properties that apply to all events SensorsAnalytics.registerSuperProperties({ app_version: '2.1.0', platform: 'react-native', build_number: 42, environment: 'production', feature_flags: ['new_ui', 'enhanced_search'] }); // Get all super properties const superProps = await SensorsAnalytics.getSuperPropertiesPromise(); console.log('Super properties:', superProps); // Output: { app_version: '2.1.0', platform: 'react-native', ... } // Remove a specific super property SensorsAnalytics.unregisterSuperProperty('feature_flags'); // Clear all super properties SensorsAnalytics.clearSuperProperties(); // Get preset properties (system-generated) const presetProps = await SensorsAnalytics.getPresetPropertiesPromise(); console.log('Preset properties:', presetProps); // Output: { $os: 'iOS', $model: 'iPhone 14', $screen_width: 390, ... } ``` -------------------------------- ### Track Push Notification IDs with React Native Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt This snippet illustrates how to track push notification identifiers for users in React Native using the SensorsAnalytics SDK. It includes examples for saving JPush IDs, FCM tokens, and APNS/Huawei tokens, as well as unsetting them and tracking push notification engagement events. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; import JPushModule from 'jpush-react-native'; // Save push notification ID (e.g., JPush) JPushModule.getRegistrationID((registrationId) => { if (registrationId) { SensorsAnalytics.profilePushId('jpush_id', registrationId); console.log('JPush ID saved:', registrationId); } }); // Save FCM token async function saveFCMToken() { try { const fcmToken = await getFCMToken(); // Assume getFCMToken is defined elsewhere SensorsAnalytics.profilePushId('fcm_token', fcmToken); } catch (error) { console.error('Failed to get FCM token:', error); } } // Save multiple push service IDs SensorsAnalytics.profilePushId('apns_token', 'apple_push_token_xyz'); SensorsAnalytics.profilePushId('huawei_token', 'huawei_push_token_abc'); // Remove push ID when user opts out SensorsAnalytics.profileUnsetPushId('jpush_id'); SensorsAnalytics.profileUnsetPushId('fcm_token'); // Track push notification engagement SensorsAnalytics.track('PushNotificationReceived', { campaign_id: 'CAMPAIGN_123', notification_type: 'promotional', title: 'Flash Sale Alert' }); ``` -------------------------------- ### SDK Initialization Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Initializes the Sensors Data SDK with various configuration options for server URL, logging, auto-tracking, and platform-specific settings. ```APIDOC ## SDK Initialization ### Description Initializes the Sensors Data SDK with configuration options including server URL, logging, auto-tracking, and platform-specific settings. ### Method `SensorsAnalytics.init(options)` ### Parameters #### Request Body - **options** (object) - Required - Configuration object for the SDK. - **server_url** (string) - Required - The URL of the analytics server. - **show_log** (boolean) - Optional - Enables or disables console logging. - **flush_interval** (number) - Optional - Interval in milliseconds to flush cached events. - **flush_bulksize** (number) - Optional - Maximum number of events to batch before flushing. - **encrypt** (boolean) - Optional - Enables data encryption. - **javascript_bridge** (boolean) - Optional - Enables H5 tracking bridge. - **heat_map** (boolean) - Optional - Enables click heatmap tracking. - **auto_track** (number) - Optional - Bitmask to enable different auto-tracking events (e.g., START(1), END(2), CLICK(4), VIEW_SCREEN(8)). - **global_properties** (object) - Optional - Global properties to be added to all events. - **android** (object) - Optional - Android-specific configurations. - **max_cache_size** (number) - Optional - Maximum cache size in bytes for Android. - **jellybean** (boolean) - Optional - Compatibility setting for older Android versions. - **sub_process_flush** (boolean) - Optional - Whether to flush events from sub-processes. - **ios** (object) - Optional - iOS-specific configurations. - **max_cache_size** (number) - Optional - Maximum number of events to cache on iOS. - **visualized** (object) - Optional - Visualized tracking configurations. - **auto_track** (boolean) - Optional - Enables automatic tracking for visualized features. - **properties** (boolean) - Optional - Enables tracking of properties for visualized features. ### Request Example ```javascript SensorsAnalytics.init({ server_url: 'https://your-analytics-server.com/api/collect', show_log: true, flush_interval: 15000, flush_bulksize: 100, encrypt: false, javascript_bridge: true, heat_map: true, auto_track: 15, global_properties: { app_version: '1.0.0', environment: 'production' }, android: { max_cache_size: 32 * 1024 * 1024, jellybean: false, sub_process_flush: false }, ios: { max_cache_size: 10000 }, visualized: { auto_track: true, properties: true } }); // Start data collection (Android) SensorsAnalytics.enableDataCollect(); ``` ### Response No specific response structure is defined for initialization. Success is indicated by the absence of errors. ``` -------------------------------- ### Initialize Sensors Data SDK with Configuration (JavaScript) Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Initializes the Sensors Data SDK with various configuration options. This includes server URL, logging preferences, flush intervals, auto-tracking settings, and platform-specific configurations for Android and iOS. It also enables features like H5 tracking, click heatmaps, and visual tracking. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Initialize SDK with full configuration SensorsAnalytics.init({ server_url: 'https://your-analytics-server.com/api/collect', show_log: true, flush_interval: 15000, // Upload data every 15 seconds flush_bulksize: 100, // Upload when 100 events are cached encrypt: false, javascript_bridge: true, // Enable H5 tracking heat_map: true, // Enable click heatmap auto_track: 15, // Enable all auto-tracking: START(1) + END(2) + CLICK(4) + VIEW_SCREEN(8) global_properties: { app_version: '1.0.0', environment: 'production' }, android: { max_cache_size: 32 * 1024 * 1024, jellybean: false, sub_process_flush: false }, ios: { max_cache_size: 10000 }, visualized: { auto_track: true, properties: true } }); // Start data collection (Android) SensorsAnalytics.enableDataCollect(); ``` -------------------------------- ### Configure React Native SDK Server URL at Runtime (JavaScript) Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt This snippet demonstrates how to dynamically set the server URL for the Sensors Analytics React Native SDK. It includes functions for switching between development, staging, and production environments, a fallback mechanism to a backup server upon failure, and logic for selecting regional servers based on user location. This is useful for A/B testing or adapting to different deployment environments. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Update server URL for different environments function configureEnvironment(env) { switch (env) { case 'development': SensorsAnalytics.setServerUrl('https://dev-analytics.example.com/api/collect'); break; case 'staging': SensorsAnalytics.setServerUrl('https://staging-analytics.example.com/api/collect'); break; case 'production': SensorsAnalytics.setServerUrl('https://analytics.example.com/api/collect'); break; } } // Switch to backup server on failure function switchToBackupServer() { SensorsAnalytics.setServerUrl('https://backup-analytics.example.com/api/collect'); console.log('Switched to backup analytics server'); } // Regional server selection function selectRegionalServer(region) { const servers = { 'us-east': 'https://us-east.analytics.example.com/api/collect', 'eu-west': 'https://eu-west.analytics.example.com/api/collect', 'asia-pacific': 'https://apac.analytics.example.com/api/collect' }; if (servers[region]) { SensorsAnalytics.setServerUrl(servers[region]); } } // Initialize with dynamic server configureEnvironment(process.env.NODE_ENV || 'production'); ``` -------------------------------- ### Configure Session Management: Interval and Tracking (Android - JavaScript) Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Configures session timeout and tracking behavior specifically for Android devices to accurately measure user engagement sessions. It allows setting the session interval in milliseconds, retrieving the current setting, and logging session configuration details. This is crucial for defining how long a user session is considered active. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Set session interval to 60 seconds (Android only) // If app is backgrounded for more than 60s, new session starts SensorsAnalytics.setSessionIntervalTime(60000); // Set shorter interval for high-engagement apps SensorsAnalytics.setSessionIntervalTime(15000); // 15 seconds // Set longer interval for utility apps SensorsAnalytics.setSessionIntervalTime(300000); // 5 minutes // Get current session interval setting const intervalMs = await SensorsAnalytics.getSessionIntervalTimePromise(); console.log('Session interval:', intervalMs, 'ms'); console.log('Session timeout:', intervalMs / 1000, 'seconds'); // Example: Dynamic session tracking async function logSessionInfo() { const interval = await SensorsAnalytics.getSessionIntervalTimePromise(); SensorsAnalytics.track('SessionConfigChecked', { session_timeout_seconds: interval / 1000, default_timeout: interval === 30000 }); } ``` -------------------------------- ### Implement Dynamic Super Properties with Sensors Analytics SDK Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Create dynamic properties that are evaluated at event tracking time using the Sensors Analytics SDK. This allows for real-time, context-aware property values. Properties can be updated dynamically and will be automatically included in tracked events. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Register dynamic super properties const dynamicProxy = SensorsAnalytics.registerDynamicSuperProperties(); // Set dynamic properties that change over time function updateDynamicProperties() { dynamicProxy.properties = { current_page: getCurrentPageName(), connection_type: getConnectionType(), battery_level: getBatteryLevel(), timestamp: new Date().toISOString(), memory_usage: getMemoryUsage(), is_logged_in: isUserLoggedIn() }; } // Update dynamic properties before tracking updateDynamicProperties(); // Track event - dynamic properties automatically included SensorsAnalytics.track('ButtonClicked', { button_name: 'checkout' }); // Event will include dynamic properties: current_page, connection_type, etc. // Helper functions (implementation examples) function getCurrentPageName() { return 'ProductDetailsScreen'; } function getConnectionType() { return 'wifi'; // or '4g', '5g', etc. } function getBatteryLevel() { return 0.85; // 85% } function getMemoryUsage() { return '234MB'; } function isUserLoggedIn() { return true; } ``` -------------------------------- ### Business ID Binding Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Bind and unbind business-specific IDs to user profiles for cross-system identity resolution and multi-ID tracking. This allows for associating user actions with their various business identifiers. ```APIDOC ## Business ID Binding ### Description Bind and unbind business-specific IDs to user profiles for cross-system identity resolution and multi-ID tracking. This allows for associating user actions with their various business identifiers. ### Methods - `bind(businessIdType, businessId)`: Binds a business-specific ID to the current user profile. - `unbind(businessIdType, businessId)`: Unbinds a business-specific ID from the current user profile. ### Parameters #### `bind` Method Parameters - **businessIdType** (string) - Required - The type of business ID (e.g., 'loyalty_id', 'crm_id', 'email'). - **businessId** (string) - Required - The value of the business ID. #### `unbind` Method Parameters - **businessIdType** (string) - Required - The type of business ID to unbind. - **businessId** (string) - Required - The value of the business ID to unbind. ### Request Example (bind) ```javascript SensorsAnalytics.bind('loyalty_id', 'LOYAL123456'); SensorsAnalytics.bind('email', 'user@example.com'); ``` ### Request Example (unbind) ```javascript SensorsAnalytics.unbind('loyalty_id', 'LOYAL123456'); ``` ### Response These methods do not return a value but update the user's profile with the bound or unbound IDs. ``` -------------------------------- ### Item Tracking (Product Analytics) Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Track product/item entities and their properties for e-commerce and content recommendation analytics. This includes setting item properties, updating them, and deleting them when discontinued. ```APIDOC ## Item Tracking (Product Analytics) ### Description Track product/item entities and their properties for e-commerce and content recommendation analytics. This includes setting item properties, updating them, and deleting them when discontinued. ### Methods - `itemSet(itemType, itemId, properties)`: Sets or updates properties for a given item. - `itemDelete(itemType, itemId)`: Deletes an item. ### Parameters #### `itemSet` Method Parameters - **itemType** (string) - Required - The type of item (e.g., 'product', 'article'). - **itemId** (string) - Required - The unique identifier for the item. - **properties** (object) - Required - An object containing key-value pairs of item properties. #### `itemDelete` Method Parameters - **itemType** (string) - Required - The type of item to delete. - **itemId** (string) - Required - The unique identifier of the item to delete. ### Request Example (itemSet) ```javascript SensorsAnalytics.itemSet('product', 'SKU12345', { name: 'Wireless Headphones', category: 'Electronics', brand: 'AudioPro', price: 299.99, in_stock: true, inventory_count: 45, rating: 4.5, review_count: 1203, tags: ['wireless', 'noise-cancelling', 'bluetooth'] }); ``` ### Request Example (itemDelete) ```javascript SensorsAnalytics.itemDelete('product', 'SKU12345'); ``` ### Response This method does not return a value but performs an internal tracking operation. ``` -------------------------------- ### Manage User Identity: Login, Logout, and IDs (JavaScript) Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Manages user identification within the application. This includes logging users in and out, retrieving the current login ID, distinct ID, and anonymous ID. It also allows for setting a custom anonymous ID and resetting to the default anonymous ID. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // User logs in - bind events to login ID SensorsAnalytics.login('user_12345'); // Get current login ID const loginId = await SensorsAnalytics.getLoginIdPromise(); console.log('Current login ID:', loginId); // 'user_12345' // Get distinct ID (unique user identifier) const distinctId = await SensorsAnalytics.getDistinctIdPromise(); console.log('Distinct ID:', distinctId); // Get anonymous ID const anonymousId = await SensorsAnalytics.getAnonymousIdPromise(); console.log('Anonymous ID:', anonymousId); // Set custom anonymous ID SensorsAnalytics.identify('custom_anon_12345'); // Reset to default anonymous ID SensorsAnalytics.resetAnonymousId(); // User logs out - unbind login ID SensorsAnalytics.logout(); ``` -------------------------------- ### Track and Manage E-commerce Items with React Native Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt This snippet demonstrates how to track product and content items, update their properties, and delete them using the SensorsAnalytics SDK in React Native. It covers setting item properties, updating existing items, and removing them when they are no longer relevant. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Set item properties SensorsAnalytics.itemSet('product', 'SKU12345', { name: 'Wireless Headphones', category: 'Electronics', brand: 'AudioPro', price: 299.99, in_stock: true, inventory_count: 45, rating: 4.5, review_count: 1203, tags: ['wireless', 'noise-cancelling', 'bluetooth'] }); // Update item when product info changes SensorsAnalytics.itemSet('product', 'SKU12345', { price: 249.99, // Sale price in_stock: true, inventory_count: 38, on_sale: true, discount_percentage: 16.67 }); // Track content items SensorsAnalytics.itemSet('article', 'ART789', { title: 'Top 10 Tech Trends 2024', author: 'Jane Smith', category: 'Technology', publish_date: '2024-01-15', word_count: 2500, reading_time: 10 }); // Delete item when discontinued SensorsAnalytics.itemDelete('product', 'SKU12345'); // Delete content item SensorsAnalytics.itemDelete('article', 'ART789'); ``` -------------------------------- ### User Identification and Login Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Manages user identity through login, logout, and anonymous ID operations to track user journeys across sessions. ```APIDOC ## User Identification and Login ### Description Manages user identity through login, logout, and anonymous ID operations to track user journeys across sessions. ### Method `SensorsAnalytics.login(loginId)` `SensorsAnalytics.getLoginIdPromise()` `SensorsAnalytics.getDistinctIdPromise()` `SensorsAnalytics.getAnonymousIdPromise()` `SensorsAnalytics.identify(anonymousId)` `SensorsAnalytics.resetAnonymousId()` `SensorsAnalytics.logout()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **loginId** (string) - Required - The unique identifier for the logged-in user. - **anonymousId** (string) - Required - A custom anonymous identifier for the user. ### Request Example ```javascript // User logs in - bind events to login ID SensorsAnalytics.login('user_12345'); // Get current login ID const loginId = await SensorsAnalytics.getLoginIdPromise(); console.log('Current login ID:', loginId); // 'user_12345' // Get distinct ID (unique user identifier) const distinctId = await SensorsAnalytics.getDistinctIdPromise(); console.log('Distinct ID:', distinctId); // Get anonymous ID const anonymousId = await SensorsAnalytics.getAnonymousIdPromise(); console.log('Anonymous ID:', anonymousId); // Set custom anonymous ID SensorsAnalytics.identify('custom_anon_12345'); // Reset to default anonymous ID SensorsAnalytics.resetAnonymousId(); // User logs out - unbind login ID SensorsAnalytics.logout(); ``` ### Response - **getLoginIdPromise**: Returns a Promise that resolves with the current login ID (string). - **getDistinctIdPromise**: Returns a Promise that resolves with the distinct ID (string). - **getAnonymousIdPromise**: Returns a Promise that resolves with the anonymous ID (string). ``` -------------------------------- ### Manage User Profiles with Sensors Analytics SDK Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Set and manage user profile attributes using the Sensors Analytics SDK. This allows for building comprehensive user profiles for segmentation and analysis. Functions include setting properties, incrementing numeric values, appending to lists, unsetting properties, and deleting profiles. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Set user profile properties (overwrites existing values) SensorsAnalytics.profileSet({ name: 'John Doe', email: 'john.doe@example.com', age: 28, gender: 'male', membership_level: 'premium', account_created: '2024-01-15', newsletter_subscribed: true }); // Set properties only if not already set SensorsAnalytics.profileSetOnce({ first_purchase_date: '2024-02-01', registration_source: 'mobile_app' }); // Increment numeric property SensorsAnalytics.profileIncrement('total_purchases', 1); SensorsAnalytics.profileIncrement('lifetime_value', 299.99); // Append to list property SensorsAnalytics.profileAppend('favorite_categories', ['Electronics', 'Books']); SensorsAnalytics.profileAppend('visited_stores', ['Store_NY', 'Store_LA']); // Remove specific property SensorsAnalytics.profileUnset('newsletter_subscribed'); // Delete entire user profile SensorsAnalytics.profileDelete(); ``` -------------------------------- ### Event Tracking Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Tracks custom events with optional properties to capture user actions and behaviors throughout the application. ```APIDOC ## Event Tracking ### Description Tracks custom events with optional properties to capture user actions and behaviors throughout the application. ### Method `SensorsAnalytics.track(eventName, properties)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **eventName** (string) - Required - The name of the event to track. - **properties** (object) - Optional - An object containing key-value pairs representing event properties. ### Request Example ```javascript // Track simple event SensorsAnalytics.track('ProductViewed'); // Track event with properties SensorsAnalytics.track('ProductPurchased', { product_id: 'SKU12345', product_name: 'Premium Headphones', category: 'Electronics', price: 299.99, quantity: 2, currency: 'USD', payment_method: 'credit_card', discount_applied: true, coupon_code: 'SAVE20' }); // Track event with array properties SensorsAnalytics.track('SearchPerformed', { search_query: 'wireless headphones', search_filters: ['Electronics', 'Audio', 'Wireless'], result_count: 45, search_duration_ms: 320 }); ``` ### Response No specific response structure is defined for event tracking. Success is indicated by the absence of errors. ``` -------------------------------- ### Track Custom Events with Properties (JavaScript) Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Tracks custom user events within the React Native application. Events can be tracked with optional properties to provide context about the action. This includes support for string, number, boolean, and array data types for event properties. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Track simple event SensorsAnalytics.track('ProductViewed'); // Track event with properties SensorsAnalytics.track('ProductPurchased', { product_id: 'SKU12345', product_name: 'Premium Headphones', category: 'Electronics', price: 299.99, quantity: 2, currency: 'USD', payment_method: 'credit_card', discount_applied: true, coupon_code: 'SAVE20' }); // Track event with array properties SensorsAnalytics.track('SearchPerformed', { search_query: 'wireless headphones', search_filters: ['Electronics', 'Audio', 'Wireless'], result_count: 45, search_duration_ms: 320 }); ``` -------------------------------- ### Query Auto-Tracking Status (JavaScript) Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Checks the status of various automatic event collection features, including general auto-tracking, visualized auto-tracking, and heat map (click map) functionality. This allows developers to understand which automatic event collection features are currently enabled and to conditionally set up manual tracking if needed. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Check if auto-tracking is enabled const isAutoTrackEnabled = await SensorsAnalytics.isAutoTrackEnabledPromise(); console.log('Auto-tracking enabled:', isAutoTrackEnabled); // Check if visualized auto-tracking is enabled const isVisualizedEnabled = await SensorsAnalytics.isVisualizedAutoTrackEnabledPromise(); console.log('Visualized auto-tracking enabled:', isVisualizedEnabled); // Check if heat map (click map) is enabled const isHeatMapEnabled = await SensorsAnalytics.isHeatMapEnabledPromise(); console.log('Heat map enabled:', isHeatMapEnabled); // Conditional tracking based on features async function setupAnalytics() { const features = { autoTrack: await SensorsAnalytics.isAutoTrackEnabledPromise(), visualized: await SensorsAnalytics.isVisualizedAutoTrackEnabledPromise(), heatMap: await SensorsAnalytics.isHeatMapEnabledPromise() }; console.log('Analytics features:', features); if (!features.autoTrack) { // Manually track events if auto-tracking is disabled setupManualTracking(); } } ``` -------------------------------- ### Bind and Unbind Business IDs with React Native Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt This snippet shows how to bind and unbind various business-specific identifiers to user profiles in React Native using the SensorsAnalytics SDK. This is crucial for cross-system identity resolution and tracking users across different platforms or systems. It also demonstrates tracking an event after IDs are bound. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Bind user to loyalty program ID SensorsAnalytics.bind('loyalty_id', 'LOYAL123456'); // Bind multiple business IDs SensorsAnalytics.bind('crm_id', 'CRM789012'); SensorsAnalytics.bind('email', 'user@example.com'); SensorsAnalytics.bind('phone_number', '+1234567890'); // Bind social media IDs SensorsAnalytics.bind('facebook_id', 'fb_user_123'); SensorsAnalytics.bind('google_id', 'google_user_456'); // Track event - all bound IDs are associated SensorsAnalytics.track('PurchaseCompleted', { order_id: 'ORD98765', amount: 599.99 }); // Unbind ID when no longer relevant SensorsAnalytics.unbind('facebook_id', 'fb_user_123'); // Unbind on logout SensorsAnalytics.unbind('crm_id', 'CRM789012'); SensorsAnalytics.unbind('loyalty_id', 'LOYAL123456'); ``` -------------------------------- ### Control Data Upload: Force Flush, Network Policies, and Deletion (JavaScript) Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Manages analytics data upload by allowing immediate flushing of cached events, setting network policies for uploads (e.g., WiFi, 5G, all networks), enabling or disabling network requests, and optionally deleting all local cached data. This section is relevant for controlling when and how data is sent to the server. ```javascript import SensorsAnalytics from 'sensorsdata-analytics-react-native'; // Force immediate upload of cached events SensorsAnalytics.flush(); // Set network policy for data upload (Android/iOS only) const NetworkType = { TYPE_NONE: 0, TYPE_2G: 1, TYPE_3G: 2, TYPE_4G: 4, TYPE_WIFI: 8, TYPE_5G: 16, TYPE_ALL: 255 }; // Allow upload only on WiFi and 5G const wifiAnd5G = NetworkType.TYPE_WIFI + NetworkType.TYPE_5G; // 8 + 16 = 24 SensorsAnalytics.setFlushNetworkPolicy(wifiAnd5G); // Allow upload on all networks SensorsAnalytics.setFlushNetworkPolicy(NetworkType.TYPE_ALL); // Allow upload on 4G and WiFi const fourGAndWiFi = NetworkType.TYPE_4G + NetworkType.TYPE_WIFI; // 4 + 8 = 12 SensorsAnalytics.setFlushNetworkPolicy(fourGAndWiFi); // Check and control network requests (Android only) const isNetworkEnabled = await SensorsAnalytics.isNetworkRequestEnablePromise(); console.log('Network requests enabled:', isNetworkEnabled); // Disable network requests temporarily SensorsAnalytics.enableNetworkRequest(false); // Re-enable network requests SensorsAnalytics.enableNetworkRequest(true); // WARNING: Delete all local cached data (use with caution!) SensorsAnalytics.deleteAll(); ``` -------------------------------- ### Push Notification Tracking Source: https://context7.com/sensorsdata/react-native-sensors-analytics/llms.txt Track push notification IDs for user engagement analysis and push campaign effectiveness measurement. This includes saving and unsetting push notification tokens. ```APIDOC ## Push Notification Tracking ### Description Track push notification IDs for user engagement analysis and push campaign effectiveness measurement. This includes saving and unsetting push notification tokens. ### Methods - `profilePushId(pushIdType, pushId)`: Saves a push notification identifier. - `profileUnsetPushId(pushIdType)`: Removes a previously saved push notification identifier. ### Parameters #### `profilePushId` Method Parameters - **pushIdType** (string) - Required - The type of push notification ID (e.g., 'jpush_id', 'fcm_token'). - **pushId** (string) - Required - The actual push notification identifier. #### `profileUnsetPushId` Method Parameters - **pushIdType** (string) - Required - The type of push notification ID to remove. ### Request Example (profilePushId) ```javascript // Assuming jPushModule.getRegistrationID() returns a token JPushModule.getRegistrationID((registrationId) => { if (registrationId) { SensorsAnalytics.profilePushId('jpush_id', registrationId); } }); // For FCM token (example with async function) async function saveFCMToken() { const fcmToken = await getFCMToken(); // Assume getFCMToken() retrieves the token SensorsAnalytics.profilePushId('fcm_token', fcmToken); } ``` ### Request Example (profileUnsetPushId) ```javascript SensorsAnalytics.profileUnsetPushId('jpush_id'); ``` ### Response These methods do not return a value but update the user's profile with push notification information. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.