get current position in expo - react-native

I am building a project in react-native and i need to find my current location. My teacher told me to use Location.getCurrentPositionAsync. But the position I always find is: 37.421998333333335 - -122.084. because?
import React, { Component, useState} from 'react';
import {View, StyleSheet,Dimensions} from 'react-native';
import * as Location from 'expo-location';
import MapView from 'react-native-maps';
const { height } = Dimensions.get("window");
export default class TrainMap extends Component {
constructor(){
super();
this.state={location:"",latitude:null,longitude:null}
}
async locationPermissionAsync() {
let canUseLocation = false;
const grantedPermission = await Location.getForegroundPermissionsAsync()
if (grantedPermission.status === "granted") {
canUseLocation = true;
} else {
const permissionResponse = await Location.requestForegroundPermissionsAsync()
if (permissionResponse.status === "granted") {
canUseLocation = true;
}
}
if (canUseLocation) {
const location = await Location.getCurrentPositionAsync(
)
console.log("received location:", location);
this.state.location = location.coords.latitude + " - " + location.coords.longitude;
this.state.latitude=location.coords.latitude;
this.state.longitude=location.coords.longitude;
console.log("Position is: "+this.state.location)
}
}
componentDidMount() {
this.locationPermissionAsync()
};
render(){}
}
how can i get my current location?

Ahh since youre using an android emulator, the lat long which youre getting is the default one which represents the where the emulator currently is at.
YOu can change the lat long on emulator via How to emulate GPS location in the Android Emulator?
check this blog
Youll get an idea how to change, but rest assured in physical device youll get the updated lat long,

Related

Error when requesting sqlite db with react native

I just started react native with sqlite.
I have a function requesting my db but i dont get anything from it, i have an error but i dont know how to fix it
I think i have a problem when i try to connect to my db
Here is the part of my code i'm talking about:
import { useState } from 'react';
import { StatusBar,StyleSheet, Text, TextInput, View, Button, Range } from 'react-native';
import * as SQLite from 'expo-sqlite';
import Slider from '#react-native-community/slider'
const db = SQLite.openDatabase('database.db');
export default function App() {
const [range, setRange]= useState(Number);
const [valeurdB, setValeurdB]= useState(Number);
const setdB= () => {
db.transaction(txn =>
txn.executeSql('UPDATE settings SET number=? WHERE title == \'new\';',
[range],
(txn, res)=> {
console.log("db updated")
},
error=>{ console.log('Error on set ' + error.message) }
)
)
}
Here is what i get:
enter image description here
And my architecture :
enter image description here

expo-location (React-Native) : Location.getCurrentPositionAsync() never returns anything

I'm developing a cross platform mobile App.
I'm testing my code on a Android Studio emulator (google pixel 5, api level 30) and i'm using expo version : ~43.0.2 and expo-location version : ~13.0.4
I've already asked for the location permission, and it works. But when I call the following code i log "there" but never "here":
console.log("there")
const userLocation = await Location.getCurrentPositionAsync()
console.log("here")
Indeed, the function Location.getCurrentPositionAsync() seems locked
A similar issue has been know in the past according to these links:
React Native Expo-Location returns Location service unavailable during initial useEffect
https://forums.expo.dev/t/getcurrentpositionasync-doesnt-return-any-value-infinity-loading/23643
But it's also the code in the Expo doc :
https://snack.expo.dev/#charliecruzan/expo-map-and-location-example
. Bellow the entire app class :
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import {Text, TextInput, Pressable, View, Alert} from 'react-native';
import * as Location from "expo-location"
export default class App extends React.Component{
state = {
errorMessage: "",
location: {}
}
getAddress(){
return this.state.address
}
_getLocation = async ()=>{
const {status} = await Location.requestForegroundPermissionsAsync();
if (status !== "granted"){
console.log("PERMISSION LACK!")
this.setState({
errorMessage:"PERMISSION NOT GRANTED"
});
}
console.log("there")
const userLocation = await Location.getCurrentPositionAsync();
console.log("here")
console.log(JSON.stringify(userLocation))
this.setState({
location: userLocation
})
}
render(){
this._getLocation()
return (
<View>
<Text>Salut</Text>
</View>
);
}
}
What did i missed?
Add accuracy and maximumAge in parameters with Location.Accuracy.Highest and 10000 respectively as shown below:
JavaScript:
const userLocation = await Location.getCurrentPositionAsync({accuracy: Location.Accuracy.Highest, maximumAge: 10000});
The solution came from How to use getCurrentPositionAsync
function in expo-location | Tabnine.
As explained in this reddit post, the location service only works in emulators if you are logged into a google account.

Redux-Thunk unable to get props in component

I have an application with firebase connected. I am able to at each step console log and get see the data from firebase being passed around however when im in the component level it always returns empty.
import * as firebase from "firebase";
import { GET_LIST } from './types';
export const getListThunk = () => {
return (dispatch) => {
const teams = [];
const teamsObj = {};
var that = this;
var ref = firebase.database().ref('SignUp/' + "577545cf-c266-4b2e-9a7d-d24e7f8e23a5");
//var query = ref.orderByChild("uuid");
console.log("uuid thunk ");
ref.on('value', function (snapshot) {
console.log("snap ", snapshot.val())
snapshot.forEach(function (child) {
let currentlike = child.val()
console.log("schedas ", currentlike)
teams.push(currentlike);
console.log("teams ",teams);
});
dispatch({ type: GET_LIST, payload: teams})
})
}
}
At all the console log here I am able to receive the information from firebase. The console displays:
Now I checked my reducer to see if I can see my information there.
import { GET_LIST } from '../actions/types';
const INITIAL_STATE = {
jello: 'hello'
};
const listReducer = (state = INITIAL_STATE, action) => {
switch (action.type){
case GET_LIST:
console.log("action ", action.payload);
return action.payload;
default:
console.log("default ");
return state;
}
};
export default listReducer;
This console log labeled action shows the payload as well
So I am again able to see the data in the reducer payload.
Now checking my component I would assume calling this.props would show the data again however it shows up empty.
Component:
mport React, { Component } from "react";
import {
View,
StyleSheet,
Button,
SafeAreaView,
ScrollView,
Image,
TouchableOpacity,
Alert,
Animated,
FlatList
} from "react-native";
import {connect} from 'react-redux';
import { getListThunk } from '../actions';
import Form from '../components/Form';
import firebase from "firebase";
import * as theme from '../theme';
import Block from '../components/Block';
import Text from '../components/Text';
import App from "../../App";
class RenderRequests extends Component {
constructor(props) {
super(props);
this.params = this.props;
uuid2 = this.props.uuid;
}
componentWillMount(){
this.props.getListThunk();
}
componentDidMount(){
console.log("did mount " , this.params.uuid)
var uuid = this.params.uuid;
//this.props.getListThunk({uuid});
}
render() {
console.log("Component level array " ,this.props)
return (
<View>
<Text> {this.params.uuid} </Text>
</View>
);
}
}
export default connect(null, { getListThunk })(RenderRequests);
Now console login this shows an empty array:
NOTE the UUID in that log file is a UUID I passed as a prop from the previous screen. As you can see the "getListThunk" is empty.
--------EDIT------------------------ I have added code based on what Vinicius Cleves has said. However I had to make it {list: state} instead of {list: state.listReducer}
I now see it in my console. However, it seems like it shows up then runs the default action and my state gets reset to nothing. Below is a screenshot of my console:
If you see my reducer code I am logging when the default action is being called. Why is it being called so many times after the initial 'GET_LIST' action gets called. This keeps replacing my state with the default state.
getListThunk is a function, as expected. To access the information as you want in this.props, you should provide a mapStateToProps function to connect.
export default connect(
state=>({someVariableName: state.listReducer}),
{ getListThunk }
)(RenderRequests);
Now, the information you were missing on this.props will show under this.props.someVariableName

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

How to get the device token in 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.