> ## Documentation Index
> Fetch the complete documentation index at: https://moengage.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Tracking User Attributes and User Identity

> Track user attributes and set identifiers for identity resolution in the React Native SDK.

User attributes are pieces of information you know about a user. They could be demographics such as age and gender, account-specific like plan, or whether a user has seen a particular A/B test variation. User attributes are customer properties you can reference throughout the customer's lifecycle.

## Difference Between User Attributes and User Identifiers

User attributes and user identifiers serve different purposes in MoEngage: 

**User Identifiers:**

User identifiers are unique values that persist across multiple sessions and devices, allowing MoEngage to recognise a user as the same individual, even when they switch between different platforms or log in later. This process, known as identity resolution, is crucial for maintaining a unified user profile, providing a consistent user experience, and tracking user behaviour accurately.

Common examples of user identifiers include:

* Email address: A user's email address is a widely used identifier because it is unique to the individual and remains consistent across different platforms.
* Phone number: Similar to email addresses, phone numbers can serve as unique identifiers, especially in mobile applications.
* User ID: MoEngage assigns each user a unique ID upon registration. This ID is used as a reliable identifier within the MoEngage platform.
* Customer ID: In e-commerce and customer relationship management (CRM) systems, a customer ID is assigned to track individual customers across various interactions.

These identifiers are set using the ***identifyUser()*** method.

By default, parameter ***ID*** is the identifier used for your workspaces, unless [Identity resolution](https://www.moengage.com/docs/user-guide/data/user-data/unified-identity-identity-resolution#overview) is enabled and identifiers are activated in your workspace.

**User Attributes**:

Descriptive information about a user that enhances their profile - Used for segmentation, personalisation, and analytics - Examples: name, age, gender, preferences, purchase history - Set using dedicated methods like ***setFirstName()*** or ***setUserAttribute()*** - Help create personalised user experiences 

In simple terms, identifiers answer "Who is this user?" while attributes answer "What do we know about this user?"

## Powering MoEngage Features

User attributes and identifiers are crucial for leveraging MoEngage effectively:

* **Segmentation:**
  * Use attributes to create targeted user groups based on demographics, behavior, etc.
  * Example: Segment users by age, purchase history for specific campaigns.
* **Personalisation:**
  * Identifiers ensure consistent user experience across devices.
  * Attributes enable tailored content (messages, recommendations).
  * Example: Personalise emails with names, recommend relevant products.
* **Analytics:**
  * Attributes provide context to user actions and behavior data.
  * Analyze conversion rates by segments, feature engagement by demographics.
  * Gain deeper insights for data-driven decisions.

By using attributes and identifiers, you can build more relevant and engaging user experiences.

# Implementing Login/Logout

For SDK versions below 11.2.00 refer to this document.

## Login User

**Single Identifier**

If your application relies on a single unique user identifier, such as an email ID for login, use the API below to pass the identifier to the MoEngage SDK

<CodeGroup>
  ```javascript JavaScript theme={null}
  import ReactMoE from 'react-native-moengage';
  ReactMoE.identifyUser("abc@xyz.com"); //Pass any unique value for your user
  ```
</CodeGroup>

**Note**: If a key is not specified, the SDK defaults to `uid`, the unique user identifier in MoEngage.

**Multiple Identifiers**

If your application supports multiple login identifiers, such as an email ID, user ID, or mobile number, pass all relevant identifiers to the SDK using the following function:

<CodeGroup>
  ```javascript JavaScript theme={null}
  import ReactMoE from 'react-native-moengage'
  	ReactMoE.identifyUser({"uid": "react-native","u_em": "react-native@moengage.com"});
  ```
</CodeGroup>

<Info>
  Updates are made to SDK functions to improve user identification and session management.

  * **Forced Logout**: The MoEngage SDK no longer automatically logs out the previous user when a new user is detected on the device. Logout should now be explicitly called for workspaces enabled with Identity resolution to avoid data corruption.
  * **SetUniqueID**: *IdentifyUser* function supports multiple identifiers, which replaces the need of using *SetUniqueID* function for user identification. Note that *SetUniqueID* is marked for removal in the future releases of SDK versions - it is important to use *identifyUser* instead especially if you are using Identity resolution in your workspace.
  * **SetAlias**: For workspaces with the Identity resolution feature enabled, MoEngage SDK stores the previous identifier values. When *IdentifyUser* function is used to track the new identifier values, MoEngage SDK detects the change in identifier value and reports accordingly.
  * If you call the *IdentifyUser* function without logging out, then the existing logged-in user's ID is updated.
</Info>

**Note**: Before implementing ***identifyUser()*** with multiple identifiers, you must activate the defined identifiers on the MoEngage dashboard. For configuration steps, see [this documentation](https://www.moengage.com/docs/user-guide/data/user-data/unified-identity-identity-resolution#configure-multiple-identifiers).

***Behaviour of Multiple identifyUser() calls***

* When calling ***identifyUser()*** multiple times, the new identifiers are appended to the existing list rather than replacing them. Here's an example of how this works:

<CodeGroup>
  ```javascript JavaScript theme={null}
  import ReactMoE from 'react-native-moengage';
              //First call with email
              ReactMoE.identifyUser({"u_em":"abc@xyz.com"});
            //Later call identifyUser() with mobile Number
            ReactMoE.identifyUser({"u_mb":"999999999"});
            //Result now the user has both email and mobile identifiers;
  ```
</CodeGroup>

* If you call ***identifyUser()*** with an identifier key that already exists, the new value will be update the existing one. Here's an example of how this works:

<CodeGroup>
  ```javascript JavaScript theme={null}
  import ReactMoE from 'react-native-moengage';
              //First call with initial email
              ReactMoE.identifyUser({"u_em":"abc@xyz.com"});
            //Later call identifyUser() when User updates their email
            ReactMoE.identifyUser({"u_em":"jfk@xyz.com"});
            //Result now the user email is updated with the later one;
  ```
</CodeGroup>

This behaviour allows you to:

* Add new identifiers as they become available
* Update specific identifiers without affecting others
* Build a complete user identity profile over time

Here, `u_em`, `u_mb` are standard user attributes. Please refer to [this section](/developer-guide/react-native-sdk/data-tracking/tracking-user-attributes-and-user-identity) to identify user with more standard user attributes

## Standard and Custom Attributes

**Standard attributes:** These are common user attributes that are pre-defined within the MoEngage dashboard, such as email address and mobile phone number. The table below lists these standard attributes and their corresponding key names

| User Attribute Name      | Key name to be used in identifyUser method |
| ------------------------ | ------------------------------------------ |
| ID                       | uid                                        |
| Email (Standard)         | u\_em                                      |
| Gender                   | u\_gd                                      |
| Birthday                 | u\_bd                                      |
| Name                     | u\_n                                       |
| First Name               | u\_fn                                      |
| Last Name                | u\_ln                                      |
| Mobile Number (Standard) | u\_mb                                      |

**Custom attributes:**  These are attributes that you define yourself within the MoEngage dashboard in addition to the standard attributes. Here's an example of how you might work with custom attributes:

<CodeGroup>
  ```javascript JavaScript theme={null}
  import ReactMoE from 'react-native-moengage';
        
  //replace custom_attribute_name with the actual name of your custom user attribute and attributeValue with the actual value you want to assign to the attribute
        
  ReactMoE.identifyUser({ custom_attribute_name: 'attributeValue' });
        
  //you can set two or more identities at the same time
        
  ReactMoE.identifyUser({ cust_attr_1: 'value1', cust_attr_2: 'value2' });
        
  //you can set custom user identity and standard user identity at the same time
        
  ReactMoE.identifyUser({ cust_attr_1: 'value1', cust_attr_2: 'value2', u_em: 'emailValue@emailDomain.com' });
  ```
</CodeGroup>

For detailed instructions on selecting both custom and standard attributes when configuring multiple identifiers, please refer to [this document](https://www.moengage.com/docs/user-guide/data/user-data/unified-identity-identity-resolution#step-1-select-identifiers).

## Logout User

<CodeGroup>
  ```javascript JavaScript theme={null}
  import ReactMoE from 'react-native-moengage';
  ReactMoE.logout();
  ```
</CodeGroup>

<Warning>
  **Critical - Very Important Integration Guideline**

  Never use both the login methods - `identifyUser` and `setUserUniqueID()`(method to assign identifier present in versions below 11.2.0) in your project. Use only either one of the methods. Using both the methods can lead to inconsistent user profile creation and merging in your MoEngage account.
</Warning>

### Logout Callback Listener

To receive a callback when logout is complete, register a listener for the `logoutComplete` event:

<CodeGroup>
  ```javascript JavaScript theme={null}
  ReactMoE.setEventListener("logoutComplete", (data) =>
    console.log(("Logout completed", data)
    // process your logout complete here
  );
  ```
</CodeGroup>

<Note>
  The logout callback listener requires React Native SDK version 12.8.0 or later.
</Note>

# Tracking User Attributes

Use the following helper methods to set User attributes like Name, Email, Mobile, Gender, etc.

<CodeGroup>
  ```javascript JavaScript theme={null}
  import ReactMoE, {
    MoEGeoLocation,
  } from "react-native-moengage";

  ReactMoE.setUserName("abc");
  ReactMoE.setUserFirstName("abc");
  ReactMoE.setUserLastName("xyz");
  ReactMoE.setUserEmailID("abc@xyz.com");
  ReactMoE.setUserContactNumber(1234567890);
  ReactMoE.setUserGender("Male"); // OR Female
  // Format - ISO-8601 String
  ReactMoE.setUserBirthday("1970-01-01T12:00:00Z");
  // For Location use MoEGeoLocation instance
  ReactMoE.setUserLocation(new MoEGeoLocation(77.3201, -77.3201));
  // For array of integers
  ReactMoE.setUserAttribute("arrayOfInt",[1,2,3]);
  // For array of strings
  ReactMoE.setUserAttribute("arrayOfString",['sample1','sample2','sample3']);
  ```
</CodeGroup>

For setting other User Attributes you can use the generic method ***setUserAttribute(key,value)***

To set custom user attributes, you will have to provide the attribute name as shown below:

<CodeGroup>
  ```javascript JavaScript theme={null}
  import ReactMoE, {
    MoEGeoLocation,
  } from "react-native-moengage";

  ReactMoE.setUserAttribute("attribute name", "attribute value");

  // For Time attribute use ISO-8601 format
  ReactMoE.setUserAttributeISODateString(
                    "time attribute name",
                    new Date().toISOString()
                  );

  // For Location, use MoEGeoLocation instance
  ReactMoE.setUserAttributeLocation(
                    "location attribute name",
                    new MoEGeoLocation(10.3223, -88.6026)
                  );
  ```
</CodeGroup>

<Info>
  You can not use "moe\_" as a prefix while naming events, event attributes, or user attributes. It is a system prefix and using it might result in periodic blacklisting without prior communication.
</Info>

## Custom Boolean User Attribute

### iOS (optional)

Starting from version 11.x.x of react-native-moengage, the default tracking for the custom boolean attribute will be changed to ***boolean(true/false)*** from ***double(0/1***). To configure this, use ***MoEAnalyticsConfig*** and pass true to track the boolean as double. By default, this is set as **false** to track the boolean as true/false.

Refer to the initialisation code snippet below.

<CodeGroup>
  ```java JavaScript theme={null}
  import ReactMoE from 'react-native-moengage';
  import { MoEInitConfig, MoEPushConfig, MoEngageLogConfig, MoEngageLogLevel } from "react-native-moengage";
  const moEInitConfig = new MoEInitConfig(
    MoEPushConfig.defaultConfig(),
    new MoEngageLogConfig(MoEngageLogLevel.DEBUG, isEnabledForReleaseBuild),
    new MoEAnalyticsConfig(true)
  );
  ReactMoE.initialize(YOUR Workspace ID, moEInitConfig);
  ```
</CodeGroup>

Refer to the example code below for tracking the boolean user attribute 

<CodeGroup>
  ```javascript JavaScript theme={null}
  import ReactMoE, {
    MoEGeoLocation,
  } from “react-native-moengage”;
        
  // If MoEAnalyticsConfig is passed as true then `boolean attribute True` will tracked with value 1 else true
  ReactMoE.setUserAttribute("boolean attribute True", true);
        
  // If MoEAnalyticsConfig is passed as true then `boolean attribute False` will tracked with value 0 else false
  ReactMoE.setUserAttribute("boolean attribute False", false);
  ```
</CodeGroup>

## Reserved keywords for User Attributes

Below is the list of keys that should not be used when tracking user attributes.

* USER\_ATTRIBUTE\_UNIQUE\_ID
* USER\_ATTRIBUTE\_USER\_EMAIL
* USER\_ATTRIBUTE\_USER\_MOBILE
* USER\_ATTRIBUTE\_USER\_NAME
* USER\_ATTRIBUTE\_USER\_GENDER
* USER\_ATTRIBUTE\_USER\_FIRST\_NAME
* USER\_ATTRIBUTE\_USER\_LAST\_NAME
* USER\_ATTRIBUTE\_USER\_BDAY
* USER\_ATTRIBUTE\_NOTIFICATION\_PREF
* USER\_ATTRIBUTE\_OLD\_ID
* MOE\_TIME\_FORMAT
* MOE\_TIME\_TIMEZONE
* USER\_ATTRIBUTE\_DND\_START\_TIME
* USER\_ATTRIBUTE\_DND\_END\_TIME
* MOE\_GAID
* MOE\_ISLAT
* INSTALL
* UPDATE
* status
* user\_id
* source

<Info>
  You can not use "moe\_" as a prefix while naming events, event attributes, or user attributes. It is a system prefix and using it might result in periodic blacklisting without prior communication.
</Info>
