### Embrace Setup with React Native Navigation (Non-Hook) Source: https://embrace.io/docs/react-native/features/navigation This example shows how to initialize and configure the Embrace SDK without using hooks, specifically for applications using `react-native-navigation`. It demonstrates manual initialization of the SDK and `EmbraceNativeTracerProvider`, and wrapping the entry view with `EmbraceNativeNavigationTracker`. ```typescript // index.ts import React, {useRef} from "react"; import {EmbraceNativeTracerProvider} from "@embrace-io/react-native-tracer-provider"; import {TracerProvider} from "@opentelemetry/api"; import {EmbraceNativeNavigationTracker} from "@embrace-io/react-native-navigation"; import {initialize} from "@embrace-io/react-native"; import {Navigation} from "react-native-navigation"; import {HomeScreen} from "screens/HomeScreen"; const initApp = async () => { // this example is showing how we can initialize Embrace not using hooks await initialize({ sdkConfig: { ios: {appId: "__YOUR_APP_ID__"}, }, }); let embraceTracerProvider: TracerProvider; try { embraceTracerProvider = new EmbraceNativeTracerProvider(); } catch (e) { console.log( "Error creating `EmbraceNativeTracerProvider`. Will use global tracer provider instead", e, ); } Navigation.registerComponent( "HomeScreen", () => (props) => { // make sure to wrap the events registry instance in a React ref const navRef = useRef(Navigation.events()); return ( { useEffect(() => { initialize({ sdkConfig: { ios: { appId: "__APP_ID__", } } }).then(hasStarted => { if (hasStarted) { // do something } }); }, []); return ... } export default App ``` -------------------------------- ### View Git Changes after Embrace SDK Setup Source: https://embrace.io/docs/react-native/4x/integration/add-embrace-sdk Displays the differences in your project's files after running the Embrace SDK setup scripts. This helps in verifying the changes made to your project. ```git git diff ``` -------------------------------- ### Run React Native Embrace SDK Setup Scripts Source: https://embrace.io/docs/react-native/4x/integration/add-embrace-sdk Executes setup scripts to integrate the Embrace SDK's native dependencies into your React Native project. Use the appropriate script for Android or iOS. ```bash node node_modules/@embrace-io/react-native/lib/scripts/setup/installAndroid.js ``` ```bash node node_modules/@embrace-io/react-native/lib/scripts/setup/installIos.js ``` -------------------------------- ### Install React Native Embrace SDK via npm Source: https://embrace.io/docs/react-native/integration/add-embrace-sdk Installs the core React Native Embrace SDK package using npm. This is the first step in integrating the SDK into your project. ```bash npm install @embrace-io/react-native ``` -------------------------------- ### Install Pods for iOS Source: https://embrace.io/docs/react-native/5x/integration/add-embrace-sdk Installs the necessary CocoaPods dependencies for the Embrace SDK on iOS. Navigate to the 'ios' directory before running this command. ```bash cd ios && pod install --repo-update ``` -------------------------------- ### Install Latest Cocoapods - iOS Source: https://embrace.io/docs/react-native/upgrading Command to update and install the latest Cocoapods for the Embrace SDK on iOS. Ensure you are in the 'ios' directory before running. ```bash cd ios && pod update EmbraceIO && pod install --repo-update ``` -------------------------------- ### Install @embrace-io/react-native-navigation with npm Source: https://embrace.io/docs/react-native/features/navigation This command installs the Embrace.io React Native Navigation package using npm. This package is essential for enabling navigation telemetry within your React Native application. ```bash npm install @embrace-io/react-native-navigation ``` -------------------------------- ### Install Embrace React Native Redux Package Source: https://embrace.io/docs/react-native/features/redux-actions Installs the necessary package for tracking Redux actions with Embrace.io in a React Native application. This package requires a Tracer Provider to be set up beforehand. ```bash npm install @embrace-io/react-native-redux ``` ```bash yarn add @embrace-io/react-native-redux ``` -------------------------------- ### Install React Native Embrace SDK via yarn Source: https://embrace.io/docs/react-native/integration/add-embrace-sdk Installs the core React Native Embrace SDK package using yarn. This is an alternative to npm for dependency management. ```bash yarn add @embrace-io/react-native ``` -------------------------------- ### Run Embrace SDK Setup Script for iOS Source: https://embrace.io/docs/react-native/integration/add-embrace-sdk Executes the JavaScript setup script to automatically modify native files for the Embrace SDK on iOS. This script is located within your node_modules directory. ```bash node node_modules/@embrace-io/react-native/lib/scripts/setup/installIos.js ``` -------------------------------- ### Install React Native Action Tracker using npm Source: https://embrace.io/docs/react-native/5x/integration/track-redux-actions This command installs the Embrace.io React Native Action Tracker package using the npm package manager. This package enables the collection of Redux actions for session context in Embrace. ```bash npm install @embrace-io/react-native-action-tracker ``` -------------------------------- ### Install @embrace-io/react-native-navigation with yarn Source: https://embrace.io/docs/react-native/features/navigation This command installs the Embrace.io React Native Navigation package using yarn. This package is essential for enabling navigation telemetry within your React Native application. ```bash yarn add @embrace-io/react-native-navigation ``` -------------------------------- ### Start Embrace SDK in Android MainApplication Source: https://embrace.io/docs/react-native/4x/integration/session-reporting Initializes and starts the Embrace SDK in the `MainApplication.java` file on Android. This call should be placed after `super.onCreate()` and configures the SDK for React Native applications, enabling network, crash, and metrics interception. ```java public class MainApplication extends Application implements ReactApplication { @Override public void onCreate() { super.onCreate(); // Add this line right after the super.onCreate(); Embrace.getInstance().start(this, false, Embrace.AppFramework.REACT_NATIVE); } } ``` -------------------------------- ### Install React Native Embrace SDK using Yarn Source: https://embrace.io/docs/react-native/5x/integration/add-embrace-sdk Installs the Embrace SDK for React Native using the Yarn package manager. Ensure you are in the correct project directory, especially when using Yarn workspaces. ```bash yarn add @embrace-io/react-native ``` -------------------------------- ### View Git Changes Source: https://embrace.io/docs/react-native/5x/integration/add-embrace-sdk Displays the differences in your project files using Git, allowing you to review changes made by the Embrace SDK setup scripts. ```bash git diff ``` -------------------------------- ### Run Embrace SDK Setup Script for Android Source: https://embrace.io/docs/react-native/integration/add-embrace-sdk Executes the JavaScript setup script to automatically modify native files for the Embrace SDK on Android. This script is located within your node_modules directory. ```bash node node_modules/@embrace-io/react-native/lib/scripts/setup/installAndroid.js ``` -------------------------------- ### Embrace Setup with React Navigation in React Native Source: https://embrace.io/docs/react-native/features/navigation This code demonstrates integrating the Embrace SDK with `@react-navigation/native`. It initializes Embrace, sets up the tracer provider, and uses EmbraceNavigationTracker to capture navigation events and screen attributes within a standard React Navigation setup. ```javascript import React from "react"; import {useEmbraceNativeTracerProvider} from "@embrace-io/react-native-tracer-provider"; import {EmbraceNavigationTracker} from "@embrace-io/react-native-navigation"; import { NavigationContainer, useNavigationContainerRef, } from "@react-navigation/native"; import {useEmbrace} from "@embrace-io/react-native"; const App = () => { const {isPending, isStarted} = useEmbrace({ ios: { appId: "__APP_ID__", }, }); const {tracerProvider, isLoading: isLoadingTracerProvider} = useEmbraceNativeTracerProvider({}, isStarted); // as of now if you inspect the source code of `useNavigationContainerRef` from `@react-navigation/native` you will see that it returns `navigation.current` instead of the entire shape of a reference const navigationRefVal = useNavigationContainerRef(); // We need here the entire shape, so we re-create it and pass it down into the `ref` prop for the `EmbraceNavigationTracker` component. const navigationRef = useRef(navigationRefVal); if (isLoadingTracerProvider) { return ( Loading Tracer Provider... ); } return ( // `NavigationContainer` is waiting for what `useNavigationContainerRef` is returning (both exported from `@react-navigation/native`) {/* rest of the navigation */} ); }; export default App; ``` -------------------------------- ### Start Embrace SDK in iOS AppDelegate Source: https://embrace.io/docs/react-native/4x/integration/session-reporting Starts the Embrace SDK within the `AppDelegate.m` file on iOS. This method should be called during application launch, passing launch options and specifying the framework as React Native. Replace 'APP_ID' with your actual 5-character Embrace App ID. ```objectivec @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *) launchOptions { // Replace with your APP_ID, which is a 5-character value, e.g. "aBc45" [[Embrace sharedInstance] startWithLaunchOptions:launchOptions framework:EMBAppFrameworkReactNative]; return YES; } ``` -------------------------------- ### Start iOS Embrace SDK with Custom Capture Services Source: https://embrace.io/docs/react-native/features/otlp This Swift code demonstrates how to start the Embrace SDK on iOS with custom configurations, including the `URLSessionCaptureService` configured to ignore specific URLs. It passes the built `captureServices` along with other essential options like `appId`, `platform`, `crashReporter`, and `export` configuration to the `Embrace.setup()` method. ```swift try Embrace \ .setup( \ options: Embrace.Options( \ appId: "__YOUR APP ID__", \ platform: .reactNative, \ captureServices: servicesBuilder.build(), \ crashReporter: EmbraceCrashReporter(), \ export: OpenTelemetryExport(spanExporter: traceExporter, logExporter: logExporter) // passing the configuration into `export` \ ) \ ) .start() ``` -------------------------------- ### Install Embrace React Native SDK via Yarn Source: https://embrace.io/docs/react-native/4x/integration/add-embrace-sdk Installs the Embrace SDK for React Native using the Yarn package manager. Ensure you are in the correct project directory, especially when using Yarn workspaces. ```bash yarn add @embrace-io/react-native ``` -------------------------------- ### Install Embrace React Native SDK via NPM Source: https://embrace.io/docs/react-native/4x/integration/add-embrace-sdk Installs the Embrace SDK for React Native using the NPM package manager. The --save flag ensures the dependency is added to your package.json file. ```bash npm install @embrace-io/react-native --save ``` -------------------------------- ### Install iOS Pods for Embrace SDK Source: https://embrace.io/docs/react-native/integration/add-embrace-sdk Updates or installs the necessary CocoaPods for the Embrace SDK on iOS. This command should be run from the 'ios' directory of your project. ```bash cd ios && pod install --repo-update ``` -------------------------------- ### Install @embrace-io/react-native-otlp via npm Source: https://embrace.io/docs/react-native/features/otlp Installs the Embrace React Native OTLP package using npm. This package allows for exporting telemetry data using the OpenTelemetry Protocol. ```bash npm install @embrace-io/react-native-otlp ``` -------------------------------- ### Create a Span with a Specific Start Time Source: https://embrace.io/docs/react-native/5x/features/traces Shows how to create a span and specify its start time, which can be in the past or future. This is useful for recording operations that have already begun or will begin shortly. ```javascript import { startSpan } from '@embrace-io/react-native-spans'; // startSpan: (name: string, parentSpanId?: string, startTimeMs?:number) => Promise; const startTimeMs = new Date().getTime() const spanId = await startSpan("span-name", undefined, startTimeMs) ``` -------------------------------- ### Install iOS Pods after Podfile Update Source: https://embrace.io/docs/react-native/4x/integration/add-embrace-sdk Installs the necessary CocoaPods dependencies for your iOS project after modifying the Podfile, including the added Embrace pods. ```bash cd ios && pod install --repo-update ``` -------------------------------- ### Create a Span with a Past Start Time Source: https://embrace.io/docs/react-native/features/traces Demonstrates creating a span that is configured to have started at a specific time in the past. This is achieved by providing a 'startTime' option during span creation. ```javascript const span = tracer.startSpan("span-name", { startTime: new Date().getTime(), }); ``` -------------------------------- ### Install React Native Action Tracker using Yarn Source: https://embrace.io/docs/react-native/5x/integration/track-redux-actions This command installs the Embrace.io React Native Action Tracker package using the Yarn package manager. This package is a dependency for tracking Redux actions within Embrace sessions. ```bash yarn add @embrace-io/react-native-action-tracker ``` -------------------------------- ### Initialize Embrace SDK in iOS (Swift) Source: https://embrace.io/docs/react-native/integration/session-reporting Creates a Swift file to initialize the Embrace SDK with a specific App ID and platform. This method is called from the AppDelegate to ensure the SDK starts as soon as the application launches. Any configuration passed via JavaScript will be ignored. ```swift import Foundation import EmbraceIO @objcMembers class EmbraceInitializer: NSObject { static func start() -> Void { do { try Embrace .setup( options: Embrace.Options( appId: "__APP_ID__", // 5 digits string platform: .reactNative ) ) .start() } catch let e { print("Error starting Embrace (e.localizedDescription)") } } } ``` -------------------------------- ### Install @embrace-io/react-native-otlp via yarn Source: https://embrace.io/docs/react-native/features/otlp Installs the Embrace React Native OTLP package using yarn. This package is essential for enabling OTLP export functionality in your React Native application. ```bash yarn add @embrace-io/react-native-otlp ``` -------------------------------- ### View Git Changes after Script Execution Source: https://embrace.io/docs/react-native/integration/add-embrace-sdk Displays the differences in your project's files after a script has been executed, allowing you to verify changes made by the Embrace setup or uninstall scripts. ```bash git diff ``` -------------------------------- ### Install React Native Navigation Screen Tracker Source: https://embrace.io/docs/react-native/4x/integration/track-navigation-screens Install the Embrace.io screen tracking module specifically for React Native Navigation. This package enables Embrace to capture screen transitions when using the React Native Navigation library. ```bash yarn add @embrace-io/react-native-navigation ``` ```bash npm install @embrace-io/react-native-navigation ``` -------------------------------- ### Install React Native Orientation Tracker Source: https://embrace.io/docs/react-native/4x/integration/track-screen-orientation Installs the Embrace Screen Orientation Tracker module for React Native. This package is required to enable orientation change tracking in your application. ```bash yarn add @embrace-io/react-native-orientation-change-tracker ``` ```bash npm install @embrace-io/react-native-orientation-change-tracker ``` -------------------------------- ### Install React Native Orientation Tracker (NPM) Source: https://embrace.io/docs/react-native/5x/integration/track-screen-orientation Installs the Embrace Screen Orientation Tracker package using NPM. This command is used to add the necessary library for tracking screen orientation changes in React Native. ```bash npm install @embrace-io/react-native-orientation-change-tracker ``` -------------------------------- ### Install Embrace React Native Spans Component Source: https://embrace.io/docs/react-native/4x/features/traces Installs the Embrace React Native Spans component using either Yarn or npm package managers. This is a prerequisite for using the Traces API. ```bash yarn add @embrace-io/react-native-spans ``` ```bash npm install @embrace-io/react-native-spans ``` -------------------------------- ### Initialize Embrace SDK in iOS (Swift) Source: https://embrace.io/docs/react-native/5x/integration/session-reporting This Swift code initializes the Embrace SDK with a specified App ID and platform. It uses a do-catch block to handle potential errors during setup and startup. This is intended to be called from your AppDelegate. ```swift import Foundation import EmbraceIO @objcMembers class EmbraceInitializer: NSObject { static func start() -> Void { do { try Embrace .setup( options: Embrace.Options( appId: "YOUR-APP-ID", platform: .reactNative ) ) .start() } catch let e { print("Error starting Embrace \(e.localizedDescription)") } } } ``` -------------------------------- ### Call Embrace Initialization in iOS AppDelegate (Objective-C) Source: https://embrace.io/docs/react-native/5x/integration/session-reporting This Objective-C code shows how to import the auto-generated Swift header and call the `[EmbraceInitializer start]` method from your `AppDelegate.m|mm` file. Ensure the Swift header import is correct for your project module name. ```objectivec #import "AppDelegate.h" #import "ProductModuleName-Swift.h" ... @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [EmbraceInitializer start]; ... } ``` -------------------------------- ### Install React Native Orientation Tracker (Yarn) Source: https://embrace.io/docs/react-native/5x/integration/track-screen-orientation Installs the Embrace Screen Orientation Tracker package using Yarn. This is a dependency for tracking screen orientation changes in React Native applications. ```bash yarn add @embrace-io/react-native-orientation-change-tracker ``` -------------------------------- ### Call Native Embrace SDK Initialization in iOS AppDelegate (Objective-C) Source: https://embrace.io/docs/react-native/integration/session-reporting Integrates the native Embrace SDK initialization into an Objective-C AppDelegate. This involves importing the Swift-generated header file and calling `[EmbraceInitializer start];` at the beginning of the `application` method. Assumes the project includes Swift files and has a bridging header. ```objective-c #import "AppDelegate.h" #import "ProductModuleName-Swift.h" ... @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [EmbraceInitializer start]; // rest of the logic } ``` -------------------------------- ### Install React Native Action Tracker Source: https://embrace.io/docs/react-native/4x/integration/track-redux-actions Install the Embrace React Native Action Tracker package using either yarn or npm. This package is required to track Redux actions within the application. ```yarn yarn add @embrace-io/react-native-action-tracker ``` ```npm npm install @embrace-io/react-native-action-tracker ``` -------------------------------- ### Create a Span using Embrace React Native API Source: https://embrace.io/docs/react-native/4x/features/traces Demonstrates how to start a new span, which represents an operation within your application. The `startSpan` function takes a name and returns a span ID. ```javascript import { startSpan } from '@embrace-io/react-native-spans'; // startSpan: (name: string, parentSpanId?: string, startTimeMs?:number) => Promise; const spanId = await startSpan("parentname") ``` -------------------------------- ### Install React Navigation Screen Tracker Source: https://embrace.io/docs/react-native/4x/integration/track-navigation-screens Install the Embrace.io screen tracking module for React Navigation. This package allows Embrace to collect screen view data within your React Native application's sessions. ```bash yarn add @embrace-io/react-navigation ``` ```bash npm install @embrace-io/react-navigation ``` -------------------------------- ### Initialize Embrace SDK (React Native - No Hooks) Source: https://embrace.io/docs/react-native/integration/session-reporting Initializes the Embrace SDK on the JavaScript side of a React Native application using the `initialize` method. This setup is necessary for tracking and should be called once. It takes an `sdkConfig` object, which is ignored if native initialization has already occurred. ```javascript import React, { useEffect, useState } from 'react' import { initialize } from '@embrace-io/react-native'; const App = () => { useEffect(() => { const initEmbrace = async () => { try { const isStarted = await initialize({ sdkConfig: { ios: { appId: "abcdf", }, }, }); if (isStarted) { // do something } } catch { console.log("Error initializing Embrace SDK"); } }; initEmbrace(); }); // regular content of the application return ( ... ); } export default App ``` -------------------------------- ### Create a Span with Custom Start Time in React Native Source: https://embrace.io/docs/react-native/4x/features/traces Shows how to create a span and specify its start time, which can be in the past or future. This is useful for recording operations that have already occurred or will occur. ```javascript import { startSpan } from '@embrace-io/react-native-spans'; // startSpan: (name: string, parentSpanId?: string, startTimeMs?:number) => Promise; const startTimeMs = new Date().getTime() const spanId = await startSpan("parentname", undefined, startTimeMs) ``` -------------------------------- ### Implement OTLP Export with Embrace and Grafana Cloud Source: https://embrace.io/docs/react-native/features/otlp Example implementation of the Embrace React Native SDK with OTLP export configuration for Grafana Cloud. It sets up log and trace exporters with specific endpoints and authorization headers. ```javascript import React, {useEffect, useMemo, useState} from "react"; import {useEmbrace} from "@embrace-io/react-native"; import {View, Text} from "react-native"; import {Stack} from "expo-router"; const GRAFANA_TOKEN = "__GRAFANA_TOKEN__"; // `grafana_instance:token` converted into a base64 string. const EXPORTER_CONFIG = { logExporter: { endpoint: "https://otlp-gateway-prod-us-central-0.grafana.net/otlp/v1/logs", headers: [ { key: "Authorization", token: `Basic ${GRAFANA_TOKEN}`, }, ], }, traceExporter: { endpoint: "https://otlp-gateway-prod-us-central-0.grafana.net/otlp/v1/traces", headers: [ { key: "Authorization", token: `Basic ${GRAFANA_TOKEN}`, }, ], }, }; // iOS is configurable through code, Android configuration happens at build time const IOS_SDK_CONFIG = {appId: "__APP_ID__"}; function RootLayout() { const {isPending, isStarted} = useEmbrace({ ios: IOS_SDK_CONFIG, exporters: EXPORTER_CONFIG, }); if (isPending) { return ( Loading Embrace ); } else { if (!isStarted) { console.log("An error occurred during Embrace initialization"); } } // regular content of the application return ( ); } export default RootLayout; ``` -------------------------------- ### Remove Native iOS SDK Initialization (Objective-C) Source: https://embrace.io/docs/react-native/upgrading In Objective-C projects, remove the existing Embrace SDK initialization line from your `AppDelegate.m` or `AppDelegate.mm` file. The previous method involved calling `[[Embrace sharedInstance] startWithLaunchOptions:launchOptions framework:EMBAppFrameworkReactNative];`. ```objectivec [[Embrace sharedInstance] startWithLaunchOptions:launchOptions framework:EMBAppFrameworkReactNative]; ``` -------------------------------- ### Get Embrace Tracer Provider Hook Source: https://embrace.io/docs/react-native/features/traces Demonstrates how to get the Embrace tracer provider using the 'useEmbraceNativeTracerProvider' hook in a React Native component. It also includes logic to handle the Embrace SDK initialization status. ```javascript import {useEmbraceNativeTracerProvider} from "@embrace-io/react-native-tracer-provider"; import {useEmbrace} from "@embrace-io/react-native"; const {isPending, isStarted} = useEmbrace({ ios: { appId: "__APP_ID__", }, }); if (isPending) { return ( Loading Embrace ); } else { if (!isStarted) { console.log("An error occurred during Embrace initialization"); } } const {tracer} = useEmbraceNativeTracerProvider({}, isStarted); ``` -------------------------------- ### Import Embrace SDK in iOS AppDelegate Source: https://embrace.io/docs/react-native/4x/integration/session-reporting Imports the Embrace SDK header file into the `AppDelegate.m` file for iOS applications. This is a prerequisite for initializing and starting the Embrace SDK on the native iOS platform when using React Native. ```objectivec #import ``` -------------------------------- ### Stop Span for Operation That Failed - React Native Source: https://embrace.io/docs/react-native/5x/features/traces This example shows how to stop a span and mark it as failed within a try-catch block. It imports the span functions, starts a span, and then stops it with the 'Failure' error code if an error occurs during execution. ```javascript // Stopping a specific span import { startSpan, stopSpan } from '@embrace-io/react-native-spans'; // stopSpan: (spanId: string, errorCode?: SPAN_ERROR_CODES, endTimeMs?:number) => Promise; // type SPAN_ERROR_CODES = 'None' | 'Failure' | 'UserAbandon' | 'Unknown'; // Starting a span const spanId = await startSpan("span-name") try{ // Do something that throw an error }catch(e){ // Stopping the span with an Error Code stopSpan(spanId, "Failure") } ``` -------------------------------- ### React Native Render Error Stack Trace Example Source: https://embrace.io/docs/react-native/features/render-errors This snippet shows an example of a stack trace logged by the Embrace SDK for a React Native rendering error. It illustrates how component names are presented, including potential 'Unknown' entries in release builds. ```plaintext * in Screen2 * in RCTView * in Screen1 * in AppContainer ``` ```plaintext * in Unknown * in RCTView * in Unknown * in AppContainer ``` -------------------------------- ### Embrace Setup with Expo Router in React Native Source: https://embrace.io/docs/react-native/features/navigation This snippet shows how to set up the Embrace SDK and EmbraceNavigationTracker within an Expo Router application. It initializes Embrace, registers a tracer provider, and wraps the navigation structure to track screen transitions and associated attributes. ```javascript import React from "react"; import {useEmbraceNativeTracerProvider} from "@embrace-io/react-native-tracer-provider"; import {EmbraceNavigationTracker} from "@embrace-io/react-native-navigation"; import {useNavigationContainerRef} from "expo-router"; import {useEmbrace} from "@embrace-io/react-native"; const App = () => { const {isPending, isStarted} = useEmbrace({ ios: { appId: "__APP_ID__", }, }); // make sure a tracer provider is registered BEFORE you attempt to record the first span (otherwise somo initial telemetrt can be missed). const {tracerProvider, isLoading: isLoadingTracerProvider} = useEmbraceNativeTracerProvider({}, isStarted); const expoNavigationRef = useNavigationContainerRef(); if (isLoadingTracerProvider) { return ( Loading Tracer Provider... ); } return ( {/* rest of the navigation */} ); }; export default App; ``` -------------------------------- ### Record Completed Span in React Native Source: https://embrace.io/docs/react-native/features/traces The `recordCompletedSpan` function allows you to start and stop a span in a single call for operations that have already completed. It accepts the tracer instance, span name, and an options object containing startTime, endTime, attributes, events, and parent span. Ensure the `@embrace-io/native-tracer-provider` package is installed. ```javascript import {recordCompletedSpan} from "@embrace-io/native-tracer-provider"; recordCompletedSpan(tracer, "my-completed-span", { startTime: previouslyStartedTime, endTime: previouslyEndedTime, attributes: { "my-attr": "foo", }, events: [ { name: "completed-span-event", attributes: {"event-attr": "bar"}, timeStamp: spanEventTime, }, ], parent: someParentSpan, }); ``` -------------------------------- ### Remove Native iOS SDK Initialization (Swift) Source: https://embrace.io/docs/react-native/upgrading In Swift projects, remove the existing Embrace SDK initialization line from your `AppDelegate.swift` file. The previous method involved calling `Embrace.sharedInstance().start(launchOptions: launchOptions, framework:.reactNative)`. ```swift Embrace.sharedInstance().start(launchOptions: launchOptions, framework:.reactNative) ``` -------------------------------- ### Get Embrace Device ID - React Native Source: https://embrace.io/docs/react-native/5x/features/current-device-id-api This snippet demonstrates how to import and use the `getDeviceId` function from the `@embrace-io/react-native` package to retrieve the Embrace Device ID. The function returns a promise that resolves with the device ID, which is then logged to the console. It's crucial to call this method after the SDK has started to ensure a valid ID is returned. ```javascript import {getDeviceId} from '@embrace-io/react-native'; const myMethod = () =>{ getDeviceId().then(deviceId =>{ console.log("Embrace Device Id", deviceId) }) } ``` -------------------------------- ### Start and End Component Views in React Native Source: https://embrace.io/docs/react-native/5x/features/tracking-components Use startView and endView to track the duration of component visibility in React Native. This allows defining custom start and end points for views, such as component mount/unmount or style changes affecting visibility. Requires '@embrace-io/react-native'. ```javascript import {startView, endView} from '@embrace-io/react-native'; startView('MyView'); endView('MyView'); ``` -------------------------------- ### Integrate React Native Navigation Screen Tracker Source: https://embrace.io/docs/react-native/4x/integration/track-navigation-screens Apply the Embrace navigation tracker to your React Native Navigation instance. This integration should be done in your application's entry point (e.g., index.js) to ensure screen tracking is active from the start. ```javascript import {Navigation} from 'react-native-navigation'; // Start - Add those lines import EmbraceNavigationTracker from '@embrace-io/react-native-navigation'; EmbraceNavigationTracker.build(Navigation); // End - Add those lines Navigation.registerComponent('myLaunchScreen', () => App); Navigation.events().registerAppLaunchedListener(() => { Navigation.setRoot({ root: { stack: { children: [ { component: { name: 'myLaunchScreen', }, }, ], }, }, }); }); ``` -------------------------------- ### Initialize Embrace SDK - Functional Component (React Native) Source: https://embrace.io/docs/react-native/5x/integration/session-reporting Initializes the Embrace SDK using React hooks in a functional component. Similar to class components, this setup tracks JavaScript errors, OTA updates, and version information. The `appId` is required for iOS. As `initialize` is asynchronous, it's best practice to handle its promise resolution using `.then()` or `await`. ```javascript import React, {useEffect, useState} from 'react' import {initialize} from '@embrace-io/react-native'; const App = () => { useEffect(() => { // Note: Initialize is a promise, so if you want to perform an action and it must be tracked, it is recommended to use await to wait for the method to finish initialize({ sdkConfig: { ios: { appId: "abcdf", } } }).then(hasStarted=>{ if (hasStarted) { // doSomething } }); },[]); return ... } export default App ``` -------------------------------- ### Uninstall Embrace SDK Implementation Source: https://embrace.io/docs/react-native/integration/add-embrace-sdk Runs a script to remove the Embrace SDK implementation from your project, whether it was added manually or by the setup scripts. This is useful for cleaning up Embrace integration. ```bash node node_modules/@embrace-io/react-native/lib/scripts/setup/uninstall.js ``` -------------------------------- ### Start and End View Tracking in React Native Source: https://embrace.io/docs/react-native/4x/features/tracking-components Tracks the mounting and unmounting of React Native components using Embrace's `startView` and `endView` functions. This allows developers to define custom view lifecycle events for performance monitoring. It requires the `@embrace-io/react-native` package. ```javascript import {startView, endView} from '@embrace-io/react-native'; startView('MyView'); endView('MyView'); ``` -------------------------------- ### Migrate useEmbraceNavigationTracker Hook to EmbraceNavigationTracker Component (React Navigation) Source: https://embrace.io/docs/react-native/features/navigation Shows the older way of using `useEmbraceNavigationTracker` hook with React Navigation. This involved creating a ref and passing it directly to the hook. This snippet serves as a comparison for the migration described in other examples. ```javascript import {useRef} from 'react' import {useEmbraceNavigationTracker} from '@embrace-io/react-navigation'; function App() { // Create the reference const navigationRef = useRef(); // Pass the reference to Embrace's Hook useEmbraceNavigationTracker(navigationRef); return ( // Assign the NavigationContainer reference value to the useRef created ); } ``` -------------------------------- ### Android Runtime Error: Embrace SDK Initialization Source: https://embrace.io/docs/react-native/upgrading This error occurs when the Android Gradle Plugin version is below the required minimum for the Embrace Gradle Plugin, leading to improper SDK initialization and data reporting issues. Ensure AGP is at least 7.4.2. ```java Error occurred while initializing the Embrace SDK. Instrumentation may be disabled. java.lang.IllegalStateException: Failed to load local config from resources. at io.embrace.android.embracesdk.internal.config.LocalConfigParser.fromResources(LocalConfigParser.kt:82) at io.embrace.android.embracesdk.internal.injection.ConfigModuleImpl.(ConfigModuleImpl.kt:25) at io.embrace.android.embracesdk.internal.injection.ConfigModuleSupplierKt.createConfigModule(ConfigModuleSupplier.kt:31) at io.embrace.android.embracesdk.internal.injection.ModuleInitBootstrapper$5.invoke(ModuleInitBootstrapper.kt:31) at io.embrace.android.embracesdk.internal.injection.ModuleInitBootstrapper$5.invoke(ModuleInitBootstrapper.kt:31) at io.embrace.android.embracesdk.internal.injection.ModuleInitBootstrapper$init$2$result$6.invoke(ModuleInitBootstrapper.kt:151) at io.embrace.android.embracesdk.internal.injection.ModuleInitBootstrapper$init$2$result$6.invoke(ModuleInitBootstrapper.kt:150) at io.embrace.android.embracesdk.internal.injection.ModuleInitBootstrapper.init(ModuleInitBootstrapper.kt:468) at io.embrace.android.embracesdk.internal.injection.ModuleInitBootstrapper.init(ModuleInitBootstrapper.kt:150) at io.embrace.android.embracesdk.internal.injection.ModuleInitBootstrapper.init$default(ModuleInitBootstrapper.kt:114) at io.embrace.android.embracesdk.EmbraceImpl.startImpl(EmbraceImpl.kt:181) at io.embrace.android.embracesdk.EmbraceImpl.start(EmbraceImpl.kt:156) at io.embrace.android.embracesdk.Embrace.start(Embrace.java:106) at com.ensemble3.MainApplication.onCreate(MainApplication.java:56) at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1192) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6712) at android.app.ActivityThread.access$1300(ActivityThread.java:237) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) Caused by: java.lang.IllegalArgumentException: No appId supplied in embrace-config.json. This is required if you want to send data to Embrace, unless you configure an OTel exporter and add embrace.disableMappingFileUpload=true to gradle.properties. at io.embrace.android.embracesdk.internal.config.LocalConfigParser.buildConfig(LocalConfigParser.kt:112) ``` -------------------------------- ### Update JavaScript Bundle Path for OTA Updates (React Native) Source: https://embrace.io/docs/react-native/upgrading If your app uses Over-The-Air (OTA) updates, call `setJavaScriptBundlePath(path: string)` to ensure properly symbolicated stack traces after CodePush support removal. This function takes the path to the new bundle as input. ```javascript setJavaScriptBundlePath(path: string); ``` -------------------------------- ### Initialize Embrace SDK in Android (Java) Source: https://embrace.io/docs/react-native/integration/session-reporting Initializes the Embrace SDK in the Android `MainApplication.java` file by calling `Embrace.getInstance().start(this);` within the `onCreate()` method, ensuring immediate data collection upon app startup. ```java import io.embrace.android.embracesdk.Embrace; ... public class MainApplication extends Application implements ReactApplication { @Override public void onCreate() { super.onCreate(); // Add this line right after the super.onCreate(); Embrace.getInstance().start(this); } } ``` -------------------------------- ### Initialize Embrace SDK in React Native (Hooks) Source: https://embrace.io/docs/react-native/4x/integration/session-reporting Initializes the Embrace SDK using React Hooks (`useEffect`). This approach ensures initialization occurs after the component mounts. The `initialize` method returns a promise, so it's advisable to use asynchronous patterns like 'await' or 'then' before executing further tracked actions. ```javascript import React, {useEffect, useState} from 'react' import {initialize} from '@embrace-io/react-native'; const App = ()=> { useEffect(()=>{ // Note: Initialize is a promise, so if you want to perform an action and it must be tracked, it is recommended to use await to wait for the method to finish initialize().then(hasStarted=>{ if(hasStarted){ //doSomething } }); },[]) return ... } export default App ``` -------------------------------- ### Initialize Embrace SDK (React Native - With Hooks) Source: https://embrace.io/docs/react-native/integration/session-reporting Initializes the Embrace SDK in a React Native application using the `useEmbrace` hook, providing a more React-idiomatic way to manage initialization. It handles loading states (`isPending`) and initialization success (`isStarted`), ensuring the SDK is set up correctly. ```javascript import React, { useEffect, useState } from 'react' import { useEmbrace } from '@embrace-io/react-native'; const App = () => { // minimum of configuration required const {isPending, isStarted} = useEmbrace({ ios: { appId: "__APP_ID__", // 5 digits string }, }); if (isPending) { return ( Loading Embrace ); } else { if (!isStarted) { console.log('An error occurred during Embrace initialization'); } } // regular content of the application return ( ... ); } export default App ``` -------------------------------- ### Initialize PushFeedback SDK and Feedback Button Source: https://embrace.io/docs/react-native/integration/add-embrace-sdk_platform=android&rn-platform=android This snippet initializes the PushFeedback SDK from a CDN and creates a custom feedback button element. It configures the button's attributes, such as project ID, modal position, and style, before appending it to the document's body. Ensure the 'pushfeedback.esm.js' script is loaded before this code executes. ```javascript const feedbackButton=document.createElement("feedback-button");feedbackButton.setAttribute("project","9ta4484qrf"),feedbackButton.setAttribute("modal-position","sidebar-right"),feedbackButton.setAttribute("button-style","dark"),feedbackButton.setAttribute("button-position","center-right"),feedbackButton.setAttribute("modal-title","Share your thoughts"),feedbackButton.setAttribute("id","default"),feedbackButton.textContent="Feedback",document.body.appendChild(feedbackButton) ``` -------------------------------- ### Manual dSYM Upload Utility (Bash) Source: https://embrace.io/docs/react-native/4x/integration/upload-symbol-files These bash commands demonstrate how to manually upload dSYM and zip files to Embrace.io using their upload utility. The commands require the App ID and API Token, and can upload a single file or multiple files by specifying them with the `--dsym` flag. ```bash # Upload a single file /EmbraceIO/upload --app $APP_ID --token $API_TOKEN dsyms.zip ``` ```bash # Upload multiple files /EmbraceIO/upload --app $APP_ID --token $API_TOKEN --dsym my_dsym --dsym my_file.zip ``` -------------------------------- ### Initialize Embrace SDK in Android Source: https://embrace.io/docs/react-native/5x/integration/session-reporting This Java code initializes the Embrace SDK within the `onCreate` method of your `MainApplication` class. It registers the application context and specifies React Native as the application framework. ```java import io.embrace.android.embracesdk.Embrace; ... public class MainApplication extends Application implements ReactApplication { @Override public void onCreate() { super.onCreate(); // Add this line right after the super.onCreate(); Embrace.getInstance().start(this, false, Embrace.AppFramework.REACT_NATIVE); } } ``` -------------------------------- ### Upload dSYMs and React Native Artifacts Source: https://embrace.io/docs/react-native/5x/integration/upload-symbol-files This command uploads dSYM files, along with the generated React Native bundle and source map, to Embrace.io. It requires your application ID, an authentication token, and the paths to the bundle and source map files. Replace ``, ``, and `` with your specific values. ```shell ios/Pods/EmbraceIO/embrace_symbol_upload. --app --token --rn-bundle ./build/main.jsbundle --rn-map ./build/main.map ``` -------------------------------- ### Call Embrace Initialization in iOS AppDelegate (Swift) Source: https://embrace.io/docs/react-native/5x/integration/session-reporting This Swift code snippet demonstrates how to call the `EmbraceInitializer.start()` method from within the `application` function in your iOS application delegate. This ensures Embrace is initialized when the app launches. ```swift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { ... func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { EmbraceInitializer.start() ... } ```