How to get the device token in react native - react-native

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?

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.

Related

react native Android Cannot access realm that has been closed

im using Realm inside my React native app, in IOS everything work fine, but with Android I always got this error: Cannot access realm that has been closed
here is my Realm:
RealmContext.js
import { ContactInfo, Room, RoomBackground, RoomDetail, RoomMessage, Summary } from "../database/RealmSchemas"
import { Realm, createRealmContext } from '#realm/react'
const config = {
schema: [Room.schema,
ContactInfo.schema,
RoomDetail.schema,
RoomBackground.schema,
Summary.schema,
RoomMessage.schema],
}
export default createRealmContext(config)
Other class
import RealmContext from '../../context/RealmContext'
const { useRealm, useQuery } = RealmContext
export class....{
const realm = useRealm()
const getRoomDetailFromDb = () => {
try {
const roomDetailDb = realm.objectForPrimaryKey('RoomDetail', room.RoomId)
if (roomDetailDb != null) {
roomDetail = JSON.parse(roomDetailDb.value)
}
} catch (error) {
console.log(error)
}
}
here is my version of realm:
"realm": "^10.18.0",
"#realm/react": "^0.3.0",
i did following the site: https://www.mongodb.com/docs/realm/sdk/react-native/use-realm-react/
Seems like react-native-reanimated lib is not compatible with Realm v10 on Android.
In case you use that please try realm#11.0.0-rc.0. It works fine after I upgrade realm version to v11. Even though it's not a stable version.

React Native Expo Location Permissions, requestForegroundPermissionsAsync, requestBackgroundPermissionsAsync how make them work

I am working on an app that records the location when the aplication is active or in the background.
After Permissions.getAsync got depricated, my app is not recording the coordonates when in background.
I understand I have to change to requestForegroundPermissionsAsync and requestBackgroundPermissionsAsync but I can not make it work.(I don't know how to use requestBackgroundPermissionsAsync)
Here is the code:
import { useState, useEffect } from 'react';
import {
Accuracy,
requestForegroundPermissionsAsync,
requestBackgroundPermissionsAsync,
watchPositionAsync
} from 'expo-location';
export default (shouldTrack, callback) => {
const [err, setErr] = useState(null);
useEffect(() => {
let subscriber;
const startWatching = async () => {
try {
const { granted } = await requestForegroundPermissionsAsync()
if (!granted) {
throw new Error('Location permission not granted');
}
subscriber = await watchPositionAsync(
{
accuracy: Accuracy.BestForNavigation,
timeInterval: 1000,
distanceInterval: 10
},
callback
);
} catch (e) {
setErr(e);
}
};
Question needs additional information to troubleshoot. For starters, are you on iOS\Android\both? Does it work on one platform but not the other? What permissions are listed in app.json (is this a managed\bare workflow)? Are the foreground updates working? Background updates require additional code and none of that is included here.
Have you gone through Expo's documentation? https://docs.expo.io/versions/latest/sdk/location

Trying to consume api using react-native

I created an api with laravel and now i want to be able to consume it using React-native but it's not working at all and I have no clue about it. Here are some code that i think can be helpful to help you try to help me.
That's my api.js file.
import {create} from 'apisauce';
import { AsyncStorage } from 'react-native';
const api = create({
baseURL:'http://127.0.0.1:8000/api',
});
api.addAsyncRequestTransform( request => async () => {
const token = await AsyncStorage.getItem('#PetFinder:token');
if(token) {
request.headers['Authorization'] = `Bearer ${token}`;
}
request.headers['Content-Type'] = `application/json`;
request.headers['accept'] = `application/json`
});
And here is my Login page
import React from 'react';
import { View, Button } from 'react-native';
import api from '../../services/api'
export default function Login() {
async function handleSubmit()
{
const response = await api.post('/login', {
email: 'nowahmst#gmail.com',
password:'123456',
});
}
return (
<View><Button onPress={handleSubmit} title="Login" > </Button></View>
);
}
Back-End is running, I'm able to get the response using postman or insomnia and my route is set to be post as well the api request.

How to Implement UPI Payment in my React-Native-App with Expo?

I want to add UPI payment in my App and currently using expo tool to create the app but now I got stuck as there is unable to find any direct implementation by using js only and require me to eject from expo. If there is any way by which I can implement the UPI without exiting from expo as it expo makes things really easy.
I have tried to implement the simple code provided in the docs for react-native-upi-payment but it is not moving ahead and require me to move through android manifest which is not inside the expo project.
import React from 'react'
import RNUpiPayment from 'react-native-upi-payment'
import { View, StyleSheet, Container } from 'react-native'
import { Input, Button } from 'react-native-elements'
import { Constants } from 'expo'
export default class PaymentScreen extends React.Component {
static navigationOptions = {
header: null
}
goToBhimUPI = () => {
RNUpiPayment.initializePayment({
vpa: 'someupi#ybl', // or can be john#ybl or mobileNo#upi
payeeName: 'Name',
amount: '1',
transactionRef: 'some-random-id'
}, this.successCallback, this.failureCallback);
}
failureCallback = (data) =>{
console.log(data)
}
successCallback = (data) => {
console.log(data)
}
render() {
return(
<Button
containerStyle = {styles.button}
type = 'clear'
title = 'Bhim UPI'
onPress = {this.goToBhimUPI}
/>
)
}
}
I expect this module to take me to the UPI payment gateway and return to the place from where it is called. Currently this is giving me error:(undefined is not an object(evaluating 'UpiModule.intializePayment'))
you can do this using react-native-upi-payment for all types of upi available or else phonepesdk for only phonepe integration

Integrating Amplitude Analytics to React Native App with Expo

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
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.
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)
}, [])
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)
}, []);