How to get the device token in react native

22,334

I tried different solutions and I've decided to use React Native Firebase.

Here you will find everything about Notifications.

Also, you can use the others libraries that come with Firebase, like Analytics and Crash Reporting

After set up the library you can do something like:

// utils/firebase.js
import RNFirebase from 'react-native-firebase';

const configurationOptions = {
  debug: true,
  promptOnMissingPlayServices: true
}

const firebase = RNFirebase.initializeApp(configurationOptions)

export default firebase


// App.js
import React, { Component } from 'react';
import { Platform, View, AsyncStorage } from 'react-native';

// I am using Device info
import DeviceInfo from 'react-native-device-info';

import firebase  from './utils/firebase';

class App extends Component {

 componentDidMount = () => {
    var language = DeviceInfo.getDeviceLocale();

    firebase.messaging().getToken().then((token) => {
       this._onChangeToken(token, language)
    });

    firebase.messaging().onTokenRefresh((token) => {
        this._onChangeToken(token, language)
    });
  }

  _onChangeToken = (token, language) => {
    var data = {
      'device_token': token,
      'device_type': Platform.OS,
      'device_language': language
    };

    this._loadDeviceInfo(data).done();
  }

  _loadDeviceInfo = async (deviceData) => {
    // load the data in 'local storage'.
    // this value will be used by login and register components.
    var value = JSON.stringify(deviceData);
    try {
      await AsyncStorage.setItem(config.DEVICE_STORAGE_KEY, value);
    } catch (error) {
      console.log(error);
    }
  };  

  render() {
    ...
  }
}

Then you can call the server with the token and all the info that you need.

Share:
22,334
achu
Author by

achu

Updated on March 15, 2020

Comments

  • achu
    achu over 4 years

    I am using react-native 0.49.3 version, My Question is how to get the device token in react native for both IOS and Android I tried with this link but it not working for me, right now I tried in IOS. how to resolve it can one tell me how to configure?