Integrating Amplitude Analytics to React Native App with Expo

2.7k Views Asked by At

I am trying to integrate Amplitude to my React Native project. I am currently still developing the application and using Expo. The first event I am trying to capture is when a user is logged in.

const events = {
  USER_LOGGED_IN: 'USER_LOGGED_IN',
  USER_CREATED_ACCOUNT: 'USER_CREATED_ACCOUNT',
};
let isInitialized = false;
const apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxx';
const initialize = () => {
  if (!Environment.isProduction || !apiKey) {
    return;
  }

  Amplitude.initialize(apiKey);
  isInitialized = true;
};

In my render function (above the return) I have this line of code:

render() {
    Expo.Amplitude.logEvent('USER_LOGGED_IN')
return (

I am not seeing any events coming into amplitude. Is it possible to see events while using expo to run my code?

Note- this code is in my home screen component

3

There are 3 best solutions below

0
On

This is what I did for amplitude to work

expo install expo-analytics-amplitude

Analytics.js

import * as Amplitude from 'expo-analytics-amplitude'

let isInitialized = false
const apiKey = 'YOUR_KEY_HERE'

export const events = {
    HOME: 'HOME'
}

export function initialize() {
    if (isInitialized || !apiKey) {
        return
    }

    Amplitude.initialize(apiKey)
    isInitialized = true
}

export function track(event, options) {
    initialize()

    if (options) {
        Amplitude.logEventWithProperties(event, options)
    } else {
        Amplitude.logEvent(event)
    }
}

export default {
    events,
    initialize,
    track
}

Import in the file where you need tracking

import Analytics from '../auth/Analytics'

...

useEffect(() => {
  Analytics.track(Analytics.events.HOME)
}, [])
0
On

You need to publish your Expo app to see the events on Amplitude because the integration works only on prod env. Once your app is published, you'll see the events on Amplitude dashboard with a small delay, usually 1 minute.

0
On

Expanding on the code above, I made a few minor updates. I will update this if I find a better way to fully integrate.

expo install expo-analytics-amplitude
import * as Amplitude from 'expo-analytics-amplitude'

let isInitialized = false
const apiKey = 'your API key'

export const events = {
    HOME: 'HOME'
}

export function initialize() {
    if (isInitialized || !apiKey) {
        return
    }

    Amplitude.initializeAsync(apiKey)
    isInitialized = true
}

export function track(event, options) {
    initialize()

    if (options) {
        Amplitude.logEventWithPropertiesAsync(event, options)
    } else {
        Amplitude.logEventAsync(event)
    }
}

export default {
    events,
    initialize,
    track
}

Import into the file you need tracking. I initialized my connection to Amplitude in App.js.

  import Analytics from "./app/auth/Analytics"; 

  useEffect(() => {
   Analytics.initialize()
   Analytics.track(Analytics.events.HOME)
  }, []);