On this page:

Related pages:

Your Rating:
Results:
PatheticBadOKGoodOutstanding!
3 rates

You use the APIs to customize the data for your app that appears in the Controller UI. This page shows you how to use the React Native Agent APIs through example code. 

React Native Agent Versions

The version number for the React Native Agent is different from that of the Controller and AppDynamics platform components. Because of this difference, see Mobile Agent Version and Deployment Support Matrix for the minimum version of the Controller and the EUM Server required for complete support of all the React Native Agent features.

Using the React Native Agent APIs

After you have installed and initialized the React Native Agent, you instrument your application code by importing the class, interface, or enumeration and then calling API methods.

Import Syntax

To access the React Native Agent APIs, use an import statement at the top of the file. The following line imports the class Instrumentation:

import { Instrumentation } from '@appdynamics/react-native-agent';

API Method Syntax

Once the class, interface, or enumeration has been imported, call the API methods from the imported component. In this example, you set custom user data with setUserDataBoolean from the Instrumentation class.

Instrumentation.setUserDataBoolean("Boolean Key", true);

Change the App Key

You can use the Native React Agent API to dynamically change the EUM app key. You receive the EUM App Key when creating a mobile app in the Controller UI. See Set Up and Access Mobile RUM for information about getting the EUM App Key.

Class

The API to change app keys is available through the Instrumentation class.

import { Instrumentation } from '@appdynamics/react-native-agent';

Methods

The API consists of the following method:

  • changeAppKey(appKey)

Method Parameters

The changeAppKey method takes the following parameter:

Parameter NameData TypeDescription
appKeystringThe EUM App Key.

Examples

In this example, you create a method that takes a new app key and passes it to the API method changeAppKey.

import { Instrumentation } from '@appdynamics/react-native-agent';
...
private updateAppKey(newAppKey) {
    Instrumentation.changeAppKey(newAppKey);
}

Collect Additional Types of Data

The React Native APIs have methods that extend the application data types you can collect and aggregate with Mobile RUM. There are six basic kinds of extensions that you can create:

Type of DataDescriptionSpecificationsWhere Data is Displayed
Info pointsHow often a method is invoked, and how long it takes to run.
  • Data is numeric
  • Names must consist of
    alphanumeric characters and/or spaces
Custom timersAny arbitrary sequence of events within your code timed,
even spanning multiple methods.
  • Data is numeric
  • Metric names must consist of
    alphanumeric characters and/or spaces
Custom metricsAny integer-based data you wish to collect.
  • Data is numeric
  • Metric names must consist of
    alphanumeric characters and/or spaces
User dataAny string key/value pair you think might be useful.
  • Data can be any type
  • Metric names have no restrictions
BreadcrumbsThe context for a crash.
  • Data can be any data type
  • Metric names have no restrictions
User interactionsCapture when users press buttons, click on lists, and select text.
  • Data can be any data type
  • Metric names have no restrictions


Report Info Points

Information points allow you to track how your own code is running. Unlike the other React Native APIs that require importing a module and using a method from that module, you add annotations to your code to report info points.

Class/Interface

The API is available through the Instrumentation class and the InfoPoint function.

import { Instrumentation, InfoPoint } from '@appdynamics/react-native-agent';

Methods

With the @InfoPoint annotation, you only need to provide a function to report info points. The @InfoPoint annotation has two signatures:

  • @InfoPoint
  • @InfoPoint({className: string, fnName: string})

Method Signatures

MethodsParametersDescription
@InfoPointNoneAutomatically reports the info points of the method that is being annotated.

@InfoPoint({className: string, fnName: string})

Object

  • className - The name of the file or module where the info point is recorded.
  • fnName - The function that invokes beginCall to track an info point.

Manually specify the class and function names to annotate.

For example: @InfoPoint({ className: 'Automobiles', fnName: 'checkInventory' })

 

Examples

The following examples show you how to use automatic and manual reporting of info points.

You are recommended to use automatic reporting if your code will not be minified: it's simpler and reports the same information. If your code will be minified, however, you should manually report the class and function names to avoid reporting the useless class and function names created by minification.

Automatic Reporting

Add the annotation @InfoPoint to automatically create an info point for the method below it. Info point reports how the method is invoked and how long it takes to run. 

 

import { Instrumentation } from '@appdynamics/react-native-agent';
...
@InfoPoint
public infoPointMethod(arg1, arg2, value) {
    console.log("Executing infoPointMethod!");
} 

Manually Reporting

To create an info point for a specific method in a class (the symbol names), pass an object to the @InfoPoint annotation that specifies the class and method name as shown below.

import { Instrumentation } from '@appdynamics/react-native-agent';
...
@InfoPoint({ className: 'MyClass', fnName: 'infoPointMethod' })
...
public infoPointMethod(arg1, arg2, value) {
    console.log("Executing infoPointMethod!");
}

Set Custom Timers

You create custom timers to time any arbitrary sequence of events within your code, even spanning multiple methods.

Class/Interface

The Custom Timers API is accessible through the Instrumentation class:

import { Instrumentation } from '@appdynamics/react-native-agent';

Methods

You create the custom timers using the following React Native Agent API methods:

  • startTimerWithName(name)

  • stopTimerWithName(name)

Method Parameters

Both methods take the following parameter:

NameTypeDescription
namestringThe name of the custom timer. Allowed characters are [A-Za-z\s0-9]. Illegal characters are replaced by their ASCII hex value.

Examples

For example, to track the time a user spends viewing a screen, the instrumentation could look like this:

import { Instrumentation } from '@appdynamics/react-native-agent';
...
private startCustomTimer() {
  Instrumentation.startTimer("My timer");
}
private stopCustomTimer() {
   Instrumentation.stopTimer("My timer");
}

Create Custom Metrics

The React Native API enables you to report custom metrics. You specify the name of the custom metric that will appear in the Controller UI.

Class

The Custom Metrics API is accessible through the Instrumentation class:

import { Instrumentation } from '@appdynamics/react-native-agent';

Methods

You create custom metrics with the reportMetric:

  • reportMetric(name, value) 

Method Parameters

The reportMetric method takes the following parameters:

NameTypeRequirementsDescription
namestringThe metric names must consist of alphanumeric characters. Illegal characters are replaced by their ASCII hex value.The name of the custom metric. 
valuenumberThe value must be a whole number, otherwise, an error will be returned.The numeric value associated with the custom metric.

Examples

For example, the following method could be used to report custom metrics:

import { Instrumentation } from '@appdynamics/react-native-agent';
...
private reportMetrics() {
    Instrumentation.reportMetric("Normal metric", 23);
    Instrumentation.reportMetric("Large metric", Number.MAX_SAFE_INTEGER + 1);
    Instrumentation.reportMetric("Small metric", Number.MIN_SAFE_INTEGER - 1);
}

Add Custom User Data

Use the Custom User Data API to set and remove key/value pairs of different data types. The key must be unique across your application.

Class

The Custom User Data API is accessible through the Instrumentation class:

import { Instrumentation } from '@appdynamics/react-native-agent';

Methods

The API provides the following methods for setting and removing custom user data:

Methods for Setting Custom User Data

  • setUserData(key, value)
  • setUserDataBoolean(key, value)
  • setUserDataDate(key, value)
  • setUserDataDouble(key, value)
  • setUserDataInteger(key, value)

 

Methods for Removing Custom User Data

  • removeUserData(key)
  • setUserDataBoolean(key)
  • setUserDataDate(key)
  • setUserDataDouble(key)
  • setUserDataInteger(key)

Method Parameters

The following table lists the parameters for the methods for setting custom user data.

Methods for Setting Custom User DataParametersData Type
setUserData

key

string

value

string || null
setUserDataBooleankeystring
valueboolean
setUserDataDatekeystring
valueDate object
setUserDataDoublekeystring
valuenumber
setUserDataIntegerkeystring
valuenumber

The following table lists the parameters for the methods for removing custom user data.

Methods for Removing Custom User DataParametersData Type
removeUserData

key

string
removeUserDataBoolean
removeUserDataDate
removeUserDataDouble
removeUserDataInteger
The method removeUserData is called when setting custom data to the value null. For example, the method Instrumentation.setUserData("name", null) will call Instrumentation.removeUserData("name").

Examples

The following code example shows how to set and remove user data with the Custom User Data API:

import { Instrumentation } from '@appdynamics/react-native-agent';
...
private setUserData() {
    Instrumentation.setUserData("userId", "AISJ1723871");
    Instrumentation.setUserDataBoolean("isVip", true);
    Instrumentation.setUserDataDate("purchaseDate", new Date(1234567890));
    Instrumentation.setUserDataDouble("monthlyVisits", 1.2345);
    Instrumentation.setUserDataInteger("totalPurchasedItems", 42);
}
private clearUserData() {
    Instrumentation.removeUserData("userId", null);
    Instrumentation.removeUserDataBoolean("isVip", null);
    Instrumentation.removeUserDataDate("purchaseDate", null);
    Instrumentation.removeUserDataDouble("monthlyVisits", null);
    Instrumentation.removeUserDataInteger("totalPurchasedItems", null);
}

Leave Breadcrumbs

Breadcrumbs enable you to situate a crash in the context of your user's experience. Set a breadcrumb when something interesting happens. If your application crashes at some point in the future, the breadcrumb will be displayed along with the crash report. Each crash report displays the most recent 99 breadcrumbs.

Class

The Breadcrumb API is accessible through the Instrumentation class:

import { Instrumentation } from '@appdynamics/react-native-agent';

Methods

You create and leave breadcrumbs with the following API method:

  • leaveBreadcrumb(breadcrumb, mode)

Method Parameters

The method leaveBreadcrumb takes the following parameters:

NameTypeDescription
breadcrumbstringThe string to include in the crash report and sessions. Truncated at 2048 characters; empty values are ignored.
modeEnumeration

The mode determining where the breadcrumb will be displayed. You can report crashes only or crashes and sessions with the following modes:

  • BreadcrumbVisibility.CRASHES_ONLY
  • BreadcrumbVisibility.CRASHES_AND_SESSIONS

The default mode is BreadcrumbVisibility.CRASHES_ONLY. If the value is invalid, the default mode will be applied.

Examples

Basic Usage

The following example shows the syntax and usage of the Breadcrumb API. 

import { Instrumentation } from '@appdynamics/react-native-agent';
...
private leaveBreadcrumb() {
    Instrumentation.leaveBreadcrumb("Drop a breadcrumb button implementation", BreadcrumbVisibility.CRASHES_AND_SESSIONS);
}

Extended Use Case

Supposed your React Native app has a wizard that shows different steps of a process sequentially on the same screen. In the case of a crash or an "Application Not Responding" (ANR) error, you would want to know what step of the wizard caused the crash or ANR.

If your app had a wizard engine similar to the one below, you could leave a breadcrumb for each screen to track events and issues.

async function wizard(...screens) {
    let currentScreen = 0;
    while (true) {
        const screen = screens[currentScreen];
        if (screen == null) return;
        // Report the current screen with AppDynamics instrumentation
        Instrumentation.leaveBreadcrumb('wizard screen ' + screen.name);
        currentScreen += await screen.action();
    }
}

The wizard engine could be used for a checkout:

wizard(
    { name: 'review cart', action:reviewCartAction },
    { name: 'chose payment', action:chosePaymentAction },
    { name: 'chose address', action:choseAddressAction },
    { name: 'review order', action:reviewOrderAction },
    { name: 'checkout', action:checkoutAction }
)

If you receive an alert that your app is triggering a lot of ANRs, you can diagnose the problem through the mobile sessions where the ANRs occur. In the session, you will see the breadcrumbs associated with the ANRs. For example, you may discover that the breadcrumbs "review cart" and "chose payment" are associated with ANRs, but "chose address" is not. Further investigation of the payment screen could lead to the discovery that the process that is encrypting credit card numbers is running on the main thread and freezing the app.

Capture User Interaction

The React Native Agent can track certain UI events triggered by user interactions. Once user interactions have been captured, you can sort sessions by UI event and view UI events in the timeline of the session waterfall. 

Supported User Interactions

You can capture when users do one or all of the following:

  • press buttons
  • select table cells
  • select text fields
  • select text views

Security and Privacy Concerns

The interaction capture mode is disabled by default for security and privacy reasons, as user interactions may contain sensitive information. Moreover, this potential security and privacy issue may be compounded if you enable both the capturing of UI interactions and screenshots. 

Class

The Interaction Capture Mode API is accessible through the InteractionCaptureMode class, but you also need the Instrumentation class to start instrumentation with the configured user capture mode.

import { Instrumentation, InteractionCaptureMode } from '@appdynamics/react-native-agent';

Properties

The following properties are accessed through the InteractionCaptureMode class and used to configure the user interaction capture. For example: InteractionCaptureMode.All

PropertyDescriptionPlatform Support
AllTrack all the user interactions.iOS, Android
ButtonPressedTrack button presses.iOS, Android
ListViewItemsSelectedTrack "List Item" clicks and focus changes for android.widget.AbsListView and its subclasses.Android
NoneDisables the tracking of any user interactions.iOS, Android
TableCellSelectedTrack table cell selection.iOS
TextFieldSelectedTrack text field selection.iOS, Android
TextViewSelectedTrack text view selection.iOS

Methods

The API methods take an array of user interaction capture modes and return an InteractionCaptureMode object that determines which user interactions will be captured. The methods do not mutate the object.

MethodDescription
withCombines the multiple user interaction capture modes.
withoutExcludes the specified user interaction modes from being captured.

Examples

Set User Interaction Mode with API Properties

The following example configures the React Native Agent to capture all user interactions.

import { Instrumentation, InteractionCaptureMode } from '@appdynamics/react-native-agent';
...
Instrumentation.start({
     appKey: <EUM_APP_KEY>,
     // ...your other configurations

     // Capture all user interactions
     interactionCaptureMode: InteractionCaptureMode.All
 })

Combine User Interaction Modes

In the following example, the with method combines the ButtonPressed (button presses) and TextFieldSelected (text field selected) modes with the None mode, effectively just enabling those two user interaction modes. 

import { Instrumentation, InteractionCaptureMode } from '@appdynamics/react-native-agent';
...
Instrumentation.start({
    appKey: <EUM_APP_KEY>,
    // ...your other configurations

    // Only enable "ButtonPressed" and "TextFieldSelected" interaction modes, and disable the rest.
    interactionCaptureMode: InteractionCaptureMode.None.with(
        InteractionCaptureMode.ButtonPressed,
        InteractionCaptureMode.TextFieldSelected
    )
})

Exclude User Interaction Modes

The following example excludes the user interaction modes ButtonPressed (button presses) and TextFieldSelected (text field selected) from the mode InteractionCaptureMode.All (all user interactions). Effectively, the React Native Agent would be configured to only capture ListViewItemSelected ("List Item" clicks), TableCellSelected (table cell selection), and TextViewSelected (text view selected) modes.

 

import { Instrumentation, InteractionCaptureMode } from '@appdynamics/react-native-agent';
...
Instrumentation.start({
    appKey: <EUM_APP_KEY>,
    // ...your other configurations

    // Include all capture modes except "ButtonPressed" and "TextFieldSelected".
    interactionCaptureMode: InteractionCaptureMode.All.without(
        InteractionCaptureMode.ButtonPressed,
        InteractionCaptureMode.TextFieldSelected
    )
})

 

Programmatically Control Sessions

By default, a mobile session ends after a period of user inactivity. For example, when a user opens your application, the session begins and only ends after the user stops using the app for a set period of time. When the user begins to use the application again, a new session begins. Instead of having a period of inactivity to define the duration of a session, however, you can use this API to programmatically control when sessions begin and end.

Class

The API is accessible through the Instrumentation class:

 

import { Instrumentation } from '@appdynamics/react-native-agent';

Methods

The API provides the following method for ending the current session and starting a new session:

MethodDescription
startNextSession()
When you call the method startNextSession from Instrumentation, the current session ends and a new session begins. The API enables you to define and frame your sessions so that they align more closely with business goals and expected user flows. For example, you could use the API to define a session that tracks a purchase of a product or registers a new user. 

Excessive use of this API will cause sessions to be throttled (excessive use is >10 calls per minute, but is subject to change). When not using the API, sessions will fall back to the default of ending after a period of user inactivity. 

Examples

In the following example, the current session ends and a new one begins when the check out is made.

import { Instrumentation } from '@appdynamics/react-native-agent';
...
private checkoutCart(){
    if (currentCartItems!=null && currentCartItems.size()>0){
	    CheckoutTask checkoutReq = new CheckoutTask();
		checkoutReq.execute(getEndpoint() + "cart/co");
		currentCartItemsMap.clear();
		convertItemsMaptoList();
        Instrumentation.startNextSession();
	} else {
	    displayToast("There are no items in the cart");
	}
}

Start and End Session Frames

You can use the React Native Agent API to create session frames that appear in the session activity. Session frames provide context for what the user is doing during a session. With the API, you can improve the names of user screens and chronicle user flows within a business context. 

Use Cases

The following are common use cases for session frames: 

  • One page performs multiple functions and you want more granular tracking of the individual functions.
  • A user flow spans multiple pages or user interactions. For example, you could use the API to create the session frames "Login", "Product Selection", and "Purchase" to chronicle the user flow for purchases.
  • You want to capture dynamic information based on user interactions to name session frames, such as an order ID.

Class/Interface

The SessionFrame API is accessible through the Instrumentation class.

import { Instrumentation } from '@appdynamics/react-native-agent';

To update the name and end a session frame, you would use the SessionFrame interface.

Methods

The following table lists the three methods you can use with session frames. In short, you start a session frame with startSessionFrame and then use updateName and end to rename and end the session frame. 

MethodDescription

startSessionFrame(name)

Starts the session frame. You call this method from Instrumentation, and it returns SessionFrame object.
updateName(name)Updates the name of the session frame. You call this method from the SessionFrame object.

Method Parameters

The methods startSessionFrame and updateName takes the following parameter:

ParametersData Type
Description

name

string

The name of the session frame.

Session Frame Example

In the following example, session frames are used to track user activity during the checkout process.

let sessionFrame: SessionFrame | undefined;

private onCheckoutCartButtonClicked() {
    // The user starts the checkout by clicking the checkout button.
    // This may be after they have updated the quantities of items in the cart, etc.
    sessionFrame = Instrumentation.startSessionFrame("Checkout");
}
private onConfirmOrderButtonClicked() {
    // Once they have confirmed payment info and shipping information, and they
    // are clicking the "Confirm" button to start the backend process of checking out,
    // we may know more information about the order itself, such as an order ID.
    if (sessionFrame) {
        sessionFrame.updateName("Checkout: Order ID " + orderId);
    }
}
private onProcessOrderCompleted() {
    // Once the order is processed, the user is done "checking out", so we end the session frame.
    if (sessionFrame) {
            sessionFrame.end();
            sessionFrame = null;
    }
}
private onCheckoutCancled() {
  // If the user cancels or returns to the cart, you'll want to end the session frame also, or else it will be
    // left open and appear to have never ended.
    sessionFrame.end();
    sessionFrame = null;
  }
}

Configure and Take Screenshots

Mobile screenshots are enabled by default. These screenshots appear in the Sessions Details dialog.

Class

The Screenshots API is accessible through the Instrumentation class:

import { Instrumentation } from '@appdynamics/react-native-agent';

Methods

The Screenshot API provides the following methods:

MethodReturn ValueDescription

takeScreenshot()

None

Asynchronously takes a screenshot of the current screen.

This will capture everything, including personal information, so you must be cautious of when to take the screenshot.

These screenshots will show up in the Sessions screen for this user.

The screenshots are taken on a background thread, compressed, and only non-redundant parts are uploaded, so it is safe to take many of these without impacting the performance of your application.

screenshotsBlocked()Promise<boolean>Returns a Boolean indicating whether screenshot capture is blocked.
blockScreenshots()Promise<void>Blocks screenshot capture and returns a Promise that resolves when screenshots are effectively blocked.
unblockScreenshots()Promise<void>

Unblocks screenshot capture if it is currently blocked. Otherwise, this has no effect.

If screenshots are disabled through AgentConfiguration.screenshotsEnabled or through the Controller UI, this method has no effect.

If screenshots are set to manual mode in the Controller UI, this method unblocks for manual mode only.

Configure Screenshots

Disable Screenshots

You can disable screenshots from the Controller UI or with the React Native API. To disable screenshots, set the property screenshotsEnabled to false when initializing the Native React Agent.

Instrumentation.start({
    appKey: <EUM_APP_KEY>,
    screenshotsEnabled: false,
    ...
});

Set On-Prem Screenshot Service

If you have deployed an on-prem EUM Server, you will need to specify the URL to the EUM Server with the property screenshotURL.

Instrumentation.start({
    appKey: <EUM_APP_KEY>,
    screenshotURL: "https://<COLLECTOR_URL>:<PORT>",
    ...
});

Examples

Take Screenshots

You can configure the Controller UI to automatically take screenshots or use the React Native API to manually take a screenshot as shown below:

private loadShoppingCart() {
  // Load shopping cart
  this.setState({
      shoppingCart: this.state.cart
  });
  // Manually take screenshot
  Instrumentation.takeScreenshot();
}

This will capture everything, including personal information, so precaution is necessary when taking screenshots

Block and Unblock Screenshots

You can also block screenshots from being taken during the execution of a code block. This just temporarily blocks screenshots from being taken until you unblock screenshots. This enables you to stop taking screenshots in situations where users are entering personal data, such as on login and account screens. 

private displayCustomerAccount() {
    // Check to see if screenshots are blocked
    if (! Instrumentation.screenshotsBlocked()) {
        // If screenshots aren't blocked, block them before showing customer details 
        Instrumentation.blockScreenshots();     
    }  
    // Code to display customer details
    
    // After you're done, unblock screenshots
    Instrumentation.unblockScreenshots();
}

Enable Logging and Set Logging Level

You enable logging by setting the logging level in the instrumentation configuration. You are recommended to disable logging for production.

Configuration Properties

You enable and set the logging level with the following configuration property:

  • loggingLevel

Logging Levels

You can set logging to one of the following levels:

EnumerationLogging LevelDescription

InstrumentationModule.LOGGING_LEVEL_NONE

NoneNo logs are displayed. This level disables logging.
InstrumentationModule.LOGGING_LEVEL_INFOInfoWarning, errors, and developer-focused messages are displayed.
InstrumentationModule.LOGGING_LEVEL_VERBOSEVerboseErrors, warnings, developer information, debugging, and troubleshooting messages are displayed.

Examples

In the following example, logging is enabled and the logging level is set to Verbose:

private async start() {
        try {
            await Instrumentation.start({
                appKey: this.state.appKey,
                loggingLevel: LoggingLevel.VERBOSE, 
                anrDetectionEnabled: true,
                interactionCaptureMode: InteractionCaptureMode.None.with(
                    InteractionCaptureMode.ButtonPressed,
                    InteractionCaptureMode.ListViewItemSelected,
                    InteractionCaptureMode.TableCellSelected,
                    InteractionCaptureMode.TextFieldSelected,
                    InteractionCaptureMode.TextViewSelected
                )
            }
        )
    }
}

React Native API Documentation

For the React Native Agent API reference documentation, see the latest React Native Agent API documentation or the previous versions: