undefined is not an object (evaluating 'this.state.user.avatar') - reactjs

Image of Error
I am using ios emulator and keep on receiving this error when i go to run the profile page. It first loads for a little bit then stops and the error pops up it says it's on the 'this.state.user.avatar' but i can't seem to see what i wrong with it? what am i doing wrong? if someone can help me that would be great!
This is my ProfileScreen.js file
import React from "react";
import {View, Text, StyleSheet, TouchableOpacity, Button, Image } from "react-native";
import Fire from '../utilities/Fire';
export default class ProfileScreen extends React.Component {
state = {
user: {}
};
unsubscribe = null;
componentDidMount() {
const user = this.props.uid || Fire.shared.uid
this.unsubscribe = Fire.shared.firestore
.collection("users")
.doc(user)
.onSnapshot(doc => {
this.setState({ user: doc.data() });
});
}
componentWillUnmount() {
this.unsubscribe();
};
render() {
return(
<View style={styles.container}>
<View style = {{ MarginTop: 64, alignItems: "Center" }}>
<View style={styles.avatarContainer}>
<Image style={styles.avatar} source={this.state.user.avatar ? { uri: this.state.user.avatar } : require("../assets/avatar.png")}
/>
</View>
<Text style={styles.name}>{this.state.user.name}</Text>
</View>
<View style={styles.subContainer}>
<View style={styles.stat}>
<Text style={styles.info}>8/10</Text>
<Text style={styles.Title}>Rewards</Text>
</View>
<View style={styles.stat}>
<Text style={styles.info}>80/100</Text>
<Text style={styles.Title}>Badges</Text>
</View>
</View>
<Button onPress={() => {Fire.shared.signOUt()}} title="Log Out" />
</View>
);
}
}
const styles = StyleSheet.create({
container:{
flex: 1,
},
avatarContainer:{
shadowColor: "#151734",
shadowRadius: 15,
shadowOpacity: 0.4
},
avatar: {
width: 136,
height: 136,
borderRadius: 68
},
name: {
marginTop: 24,
fontSize: 16,
fontWeight: "600"
},
subContainer: {
flexDirection: "row",
justifyContent: "space-between",
margin: 32,
},
stat: {
alignItems:"center",
},
info: {
color: "#4F566D",
fontSize: 18,
fontWeight: "300"
},
Title: {
color: "#C3C5CD",
fontSize: 12,
fontWeight: "500",
marginTop: 4
}
});
This is my Fire.js file
import FirebaseKeys from '../config';
import firebase from 'firebase';
require("firebase/firestore");
class Fire{
constructor() {
firebase.initializeApp(FirebaseKeys);
}
addPost = async({ text, localUri }) => {
const remoteUri = await this.uploadPhotoAsync(localUri, 'photos/${this.uid}/${Date.now()}');
return new Promise ((res, rej) => {
this.firestore
.collection("posts")
.add ({
text,
uid: this.uid,
timestamp: this.timestamp,
image: remoteUri
})
.then(ref => {
res(ref);
})
.catch(error => {
rej(error);
});
});
};
uploadPhotoAsync = async (uri, filename) => {
return new Promise(async (res, rej) => {
const response = await fetch(uri);
const file = await response.blob();
let upload = firebase
.storage()
.ref(filename)
.put(file);
upload.on(
"state_changed",
snapshot => {},
err => {
rej(err);
},
async () => {
const url = await upload.snapshot.ref.getDownloadURL();
res(url);
}
);
});
};
createUser = async user => {
let remoteUri = null
try {
await firebase.auth().createUserWithEmailAndPassword(user.email, user.password)
let db = this.firestore.collection("users").doc(this.uid)
db.set({
name: user.name,
email: user.email,
avatar: null
})
if (user.avatar) {
remoteUri = await this.uploadPhotoAsync(user.avatar, 'avatars/${this.uid}')
db.set({avatar: remoteUri }, { merge: true})
}
} catch (error) {
alert("Error: ", error);
}
};
signOut = () => {
firebase.auth().signOut();
};
get firestore(){
return firebase.firestore();
}
get uid() {
return (firebase.auth().currentUser || {}).uid;
}
get timestamp() {
return Date.now();
}
}
Fire.shared = new Fire();
export default Fire;

If you want to set the state like that you need to do it in the constructor like this:
constructor(props) {
super(props);
this.state = {
user: {}
}
}
So add that code to the top of the class and it should actually set the user to an empty object..
Everywhere else in the app you use setState....

Try to change user{} by user[]

Related

Expo app keeps returning TypeError: undefined is not an object (evaluating 'function')

I am creating a mobile app that takes a picture and then returns the objects it detected. the way it works is that i have heroku running the ml model api. the weird thing about this error is that it happened after my code worked and sent an api request which then returned a json of what it detected. and when i ran it again it gave me [TypeError: undefined is not an object (evaluating '_expo.ImageManipulator.manipulateAsync')]. i looked at the value of image and asset to see if they are undefined and the console printed false. i even tried
console.log(typeof image==='undefined')
console.log(typeof asset==='undefined')
console.log(typeof image=='undefined')
console.log(typeof asset=='undefined')
just to make sure that the value of the variables aren't undefined. i then commented out the function to see what would happen and i got [TypeError: undefined is not an object (evaluating '_this.toServer')]. i then restarted the expo server and did everything i did above again but it keeps giving me [TypeError: undefined is not an object (evaluating '_expo.ImageManipulator.manipulateAsync')]. the code below is the code for the function that saves the image and makes a post request.
const takePicture = async () => {
if (cameraRef) {
try {
const data = await cameraRef.current.takePictureAsync();
console.log(data);
setImage(data.uri);
} catch (error) {
console.log(error);
}
}
};
uriToBase64 = async (uri) => {
let base64 = await FS.readAsStringAsync(uri, {
encoding: FS.EncodingType.Base64,
});
return base64;
};
const savePicture = async () => {
if (image) {
try {
const asset = await MediaLibrary.createAssetAsync(image);
console.log(image===undefined)
console.log(asset===undefined)
console.log(image==undefined)
console.log(asset===undefined)
let manipResult = await ImageManipulator.manipulateAsync(
asset,[{ resize: { width: 800, height: 800 } }],{ format: 'jpg' });
let assetResized = await MediaLibrary.createAssetAsync(manipResult);
await this.toServer({
type:"image",
base64: uriToBase64(assetResized),
uri: assetResized,
});
setImage(null);
console.log('saved successfully');
} catch (error) {
console.log(error);
}
}
};
also if i do:
if(!(image==undefined))
to make it so that if the image is undefined it won't do anything i get
LOG [Error: Argument of an incompatible class: class java.util.HashMap cannot be passed as an argument to parameter expecting class java.lang.String.]
WARN Possible Unhandled Promise Rejection (id: 0):
Error: Argument of an incompatible class: class java.util.HashMap cannot be passed as an argument to parameter expecting class java.lang.String.
promiseMethodWrapper#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:22934:45
http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:114097:40
readAsStringAsync$#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:118249:92
tryCatch#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24610:23
http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24590:34
tryCatch#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24610:23
invoke#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24648:30
http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24672:19
tryCallTwo#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:30323:9
doResolve#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:30487:25
Promise#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:30346:14
callInvokeWithMethodAndArg#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24671:33
_invoke#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24676:157
async#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24762:69
readAsStringAsync#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:118236:38
_callee3$#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:120465:69
tryCatch#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24610:23
http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24590:34
tryCatch#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24610:23
invoke#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24648:30
http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24672:19
tryCallTwo#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:30323:9
doResolve#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:30487:25
Promise#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:30346:14
callInvokeWithMethodAndArg#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24671:33
_invoke#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24676:157
async#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24762:69
_callee3#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:120460:40
_callee5$#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:120529:36
tryCatch#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24610:23
http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24590:34
tryCatch#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24610:23
invoke#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24648:30
http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:24654:19
tryCallOne#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:30314:16
http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:30415:27
http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:31506:26
_callTimer#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:31406:17
_callReactNativeMicrotasksPass#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:31441:17
callReactNativeMicrotasks#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:31648:44
__callReactNativeMicrotasks#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:23414:46
http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:23193:45
__guard#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:23397:15
flushedQueue#http://192.168.1.4:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false:23192:21
flushedQueue#[native code]
invokeCallbackAndReturnFlushedQueue#[native code]
here is the entire code:
import React, { useState, useEffect, useRef } from 'react';
import { Text, View, StyleSheet, TouchableOpacity, Image } from 'react-native';
import Constants from 'expo-constants';
import { Camera, CameraType } from 'expo-camera';
import * as MediaLibrary from 'expo-media-library';
import { MaterialIcons } from '#expo/vector-icons';
import Button from './src/components/Button';
import axios from 'axios'
import { Buffer } from "buffer";
import * as FS from "expo-file-system";
import { ImageManipulator } from 'expo';
export default function App() {
const [hasCameraPermission, setHasCameraPermission] = useState(null);
const [image, setImage] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
const [flash, setFlash] = useState(Camera.Constants.FlashMode.off);
const cameraRef = useRef(null);
useEffect(() => {
(async () => {
MediaLibrary.requestPermissionsAsync();
const cameraStatus = await Camera.requestCameraPermissionsAsync();
setHasCameraPermission(cameraStatus.status === 'granted');
})();
}, []);
const takePicture = async () => {
if (cameraRef) {
try {
const data = await cameraRef.current.takePictureAsync();
console.log(data);
setImage(data.uri);
} catch (error) {
console.log(error);
}
}
};
uriToBase64 = async (uri) => {
let base64 = await FS.readAsStringAsync(uri, {
encoding: FS.EncodingType.Base64,
});
return base64;
};
toServer = async (mediaFile) => {
url = "censored url so that trolls wont use it ";
let response = await FS.uploadAsync(url, mediaFile.uri, {
headers: {
"content-type": "image/jpeg",
},
httpMethod: "POST",
uploadType: FS.FileSystemUploadType.BINARY_CONTENT,
});
console.log(response);
};
const savePicture = async () => {
if (image) {
try {
const asset = await MediaLibrary.createAssetAsync(image);
console.log(typeof image==='undefined')
console.log(typeof asset==='undefined')
console.log(typeof image=='undefined')
console.log(typeof asset=='undefined')
await this.toServer({
type:"image",
base64: uriToBase64(asset),
uri: asset,
});
setImage(null);
console.log('saved successfully');
} catch (error) {
console.log(error);
}
}
};
if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={styles.container}>
{!image ? (
<Camera
style={styles.camera}
type={type}
ref={cameraRef}
flashMode={flash}
>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
paddingHorizontal: 30,
}}
>
<Button
title=""
icon="retweet"
onPress={() => {
setType(
type === CameraType.back ? CameraType.front : CameraType.back
);
}}
/>
<Button
onPress={() =>
setFlash(
flash === Camera.Constants.FlashMode.off
? Camera.Constants.FlashMode.on
: Camera.Constants.FlashMode.off
)
}
icon="flash"
color={flash === Camera.Constants.FlashMode.off ? 'gray' : '#fff'}
/>
</View>
</Camera>
) : (
<Image source={{ uri: image }} style={styles.camera} />
)}
<View style={styles.controls}>
{image ? (
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
paddingHorizontal: 50,
}}
>
<Button
title="Re-take"
onPress={() => setImage(null)}
icon="retweet"
/>
<Button title="Save" onPress={savePicture} icon="check" />
</View>
) : (
<Button title="Take a picture" onPress={takePicture} icon="camera" />
)}
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#000',
padding: 8,
},
controls: {
flex: 0.5,
},
button: {
height: 40,
borderRadius: 6,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontWeight: 'bold',
fontSize: 16,
color: '#E9730F',
marginLeft: 10,
},
camera: {
flex: 5,
borderRadius: 20,
},
topControls: {
flex: 1,
},
});

Cannot update a component from inside the function body of a different component. how to fix this with react hook

I wanted to how to solve this error... this is not my code I am fixing bugs in someone else's code. "I wanted to how to dispatch to store with use effect Hook".
as I researched it says it says I can dispatch to store inside a function without a use effect Hook I wanted to know how to modify it in this code,
also if someone know how to getrid of "MapStateToProps" with the useSelect hook that will also be more helpfull for me inorder to improve this code...
LoginScreen.js
import React, { Component } from 'react';
import {
View, Text,
Image,
Dimensions,
ImageBackground,
SafeAreaView,
Alert,
Modal, Button,
StatusBar,
TextInput,
TextInputComponent,
Linking,
StyleSheet
} from 'react-native';
// import { PropTypes } from 'prop-types';
// import NetInfo from "#react-native-community/netinfo";
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
// import * as Animatable from 'react-native-animatable';
import AsyncStorage from '#react-native-community/async-storage'
import { showMessage, hideMessage } from "react-native-flash-message";
const { width, height } = Dimensions.get('window');
import styles from './styles';
import Buttons from '../../../uiElements/Buttons/RoundButtons'
import VerificationCodeText from '../../../uiElements/VerificationCodeText'
import { connect } from 'react-redux';
import startUpActions from '../../../redux/StartUp/actions';
import Loading from '../../../uiElements/Loading';
import { ScrollView, TouchableHighlight, TouchableOpacity } from 'react-native-gesture-handler';
import { textFocusColor, textDefaultColor } from '../../../contents'
import TextInputField from '../../../uiElements/TextInput';
const { loginApp, getCustomerDetailsByEmail, clearProps, getAgentExposableId } = startUpActions;
const imageWidth = Dimensions.get('window').width;
// const imageWidth = Dimensions.get('window').width;
class StartScreen extends Component {
constructor(props) {
super(props);
this.state = {
hasFocusPhoneNo: false,
iseyeactivenew: true,
iseyeactivecurrent: true,
userId: '',
password: '',
hasFocusUsername: false,
hasFocusPassword: false,
}
}
static getStateFromProps(props, state) {
if (props.jwttoken != undefined) {
if (props.jwttoken == 'errlogin') {
}
}
}
static getDerivedStateFromProps(props, state) {
if (props.jwttoken != undefined) {
if (props.jwttoken == 'errlogin') {
showMessage({
textStyle: { paddingLeft: 10 },
titleStyle: { paddingLeft: 10 },
message: "Error",
description: "Username or Password incorrect",
type: "default",
backgroundColor: "red", // background color
color: "#ffffff",
duration: 3850
});
_storeAccess = async () => {
props.dispatch(clearProps())
}
_storeAccess()
} else {
_storeAccess = async () => {
await AsyncStorage.setItem('access_token', props.jwttoken);
const appIdRequest = await AsyncStorage.getItem('appIdrequest')
props.dispatch(getCustomerDetailsByEmail(props.jwttoken, '', state.userId))
//props.dispatch(clearProps())
}
_storeAccess();
}
}
if (props.customerDetailsAllResult != undefined) {
// console.log(props.customerDetailsAllResult.responseDto.customerDetailsId)
if (props.customerDetailsAllResult.responseDto == null) {
props.dispatch(clearProps())
} else {
_storeAccess = async () => {
await AsyncStorage.setItem('customerWalletId', props.customerDetailsAllResult.responseDto.agentSenderDetailsId.toString());
await AsyncStorage.setItem('email', props.customerDetailsAllResult.responseDto.email.toString()) //not change
await AsyncStorage.setItem('useremail', props.customerDetailsAllResult.responseDto.email.toString()) //when change coporate mail this will change
await AsyncStorage.setItem('agentSenderDetails', JSON.stringify(props.customerDetailsAllResult.responseDto))
const access_token = await AsyncStorage.getItem('access_token')
Console.log("navigate", access_token)
if (access_token != null) {
props.navigation.navigate('TabView')
}
// props.navigation.navigate('MoneyTransfer2')
props.dispatch(clearProps())
}
_storeAccess();
}
}
if (props.agentExposableId != undefined) {
if (props.agentExposableId == null) {
props.dispatch(clearProps()) //loginurl https://qabankingauth.monexfintech.com/v1/auth/authenticate
} else {
_storeAccess = async () => { await AsyncStorage.setItem('agentExposableId', props.agentExposableId); }
// props.navigation.navigate('MoneyTransfer2')
props.dispatch(clearProps())
}
_storeAccess();
}
return null;
}
componentDidMount() {
// console.log('lll')
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.customerDetailsAllResult !== this.props.customerDetailsAllResult) {
}
if (prevProps.jwttoken !== this.props.jwttoken) {
console.log(this.props.jwttoken)
}
}
getData = async () => {
try {
const accesstoken = await AsyncStorage.getItem('access_token')
if (accesstoken !== null) {
this.props.dispatch(userShow(accesstoken))
this.setState({ islogin: true })
console.log('jjj')
// this.props.navigation.navigate('TabView')
} else {
this.props.dispatch(getBranchesList())
this.setState({ islogin: false })
// this.props.navigation.navigate('TabView')
}
} catch (e) {
console.log(e)
}
}
onChangeText = (key, val) => {
this.setState({ [key]: val }, () => {
})
}
onpressphoneno = () => {
this.setState({ hasFocusPhoneNo: true })
this.setState({ postcodeerror: false })
}
btnPress = async () => {
this.props.navigation.navigate('LoginScr')
if (this.state.userId == '' || this.state.password == '') {
showMessage({
textStyle: { paddingLeft: 10 },
titleStyle: { paddingLeft: 10 },
message: "Error",
description: "Please enter Username and Password",
type: "default",
backgroundColor: "red", // background color
color: "#ffffff",
duration: 3850
});
} else {
try {
const obj = {
username: this.state.userId,
password: this.state.password,
grantType: 'Agent Customer',
agentRegNumber: 'MXAG01'
}
await AsyncStorage.setItem('email', this.state.userId);
await AsyncStorage.setItem('useremail', this.state.userId);
await AsyncStorage.setItem('password', this.state.password);
await AsyncStorage.setItem('access_token', ' eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJjaGF0aHVyYW5nYUBjb2RlbGFudGljLmNvbSIsInVzZXJfaWQiOjMsImV4cCI6MTYxNTQzODI4NywiaXNfdGZhX2VuYWJsZWQiOm51bGwsImlhdCI6MTYxNTQzNDY4NywidGZhRGVmYXVsdFR5cGUiOm51bGwsImNsaWVudF9jb2RlIjoiTU4ifQ.lncV1VQ-T0dNPsME0_FvRF-2TQShHiwP66aFoT0fhV58QaR-Sn0ZVEBPSiGxxQ9NWnzbaCpev61Hkex6EPBxNA');
// this.props.dispatch(getFirstValue());
this.props.dispatch(getAgentExposableId());
this.props.dispatch(loginApp(obj))
this.props.dispatch(clearProps());
} catch (error) {
console.log(error);
}
//this.props.navigation.navigate('LoginScr')
}
}
clickPrivacypolicy() {
Linking.canOpenURL("https://spoton.money/policy-procedures-refund-terms-gdpr").then(supported => {
if (supported) {
Linking.openURL("https://spoton.money/policy-procedures-refund-terms-gdpr");
} else {
console.log("Don't know how to open URI: " + this.props.url);
}
});
}
render() {
// const { navigate } = this.props.navigation;
return (
<SafeAreaView style={style.container}>
<ScrollView style={{ backgroundColor: '#343A4F', }}>
<View style={{ backgroundColor: '#343A4F', height: '100%' }}>
<ImageBackground source={require('../../../images/ellipse.png')} style={{ width: '100%', height: '60%' }}>
<View style={{ alignItems: 'center', paddingTop: wp('15%') }}>
<Image
style={{ width: wp('45%'), height: wp('15%') }}
source={require('../../../images/spotonmoneylogo.png')}
/>
</View>
{this.props.loading && <Loading navigation={this.props.navigation} animating={true} />}
<View style={{ paddingLeft: wp('5%'), paddingRight: wp('5%'), backgroundColor: '#343A4F', marginTop: wp('50%') }}>
{/* <TextInput
placeholder="Username"
placeholderTextColor={textDefaultColor}
onFocus={() =>this.setState({ hasFocusUsername: true })}
onBlur={() => this.setState({ hasFocusUsername: false })}
onChangeText={(val) => this.setState({ userId: val })}
style={
this.state.hasFocusUsername ?
styles.focusedTextInput :
styles.txtstyle
}
/> */}
<TextInputField
placeholdertext="Username"
valuetext={this.state.email}
onFocusFunc={() => this.setState({ hasFocusUserName: true })}
onBlurFunc={() => this.setState({ hasFocusUserName: false })}
onChangeTextFunc={value => this.onChangeText('userId', value)}
iserrortext={this.state.errorlastnamestate}
editabletext={false}
keyboardType1='email'
// texterror={this.state.errorlastnametextstate}
// hasFocustext={this.state.hasFocusUserName}
/>
<TextInputField
placeholdertext="Password"
valuetext={this.state.password}
onFocusFunc={() => this.setState({ hasFocusPassword: true })}
onBlurFunc={() => this.setState({ hasFocusPassword: false })}
onChangeTextFunc={value => this.onChangeText('password', value)}
iserrortext={this.state.errorlastnamestate}
editabletext={false}
secureTextEntrytxt={true}
// texterror={this.state.errorlastnametextstate}
hasFocustext={this.state.hasFocusPassword}
/>
{/* <TextInput
placeholder="Password"
placeholderTextColor={textDefaultColor}
secureTextEntry={true}
onFocus={() => this.setState({ hasFocusPassword: true })}
onBlur={() => this.setState({ hasFocusPassword: false })}
onChangeText={(val) => this.setState({ password: val })}
style={
this.state.hasFocusPassword ?
styles.focusedTextInput :
styles.txtstyle
}
/> */}
</View>
<View style={{ paddingTop: wp('10%'), alignItems: 'center' }}>
<TouchableOpacity onPress={() => this.props.navigation.navigate('Verification')}>
<Text style={{ color: 'white' }}>Forgot Password</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.btnPress()}>
<Buttons text="Log In" btnfontSize={wp('4%')}
btnbackgroundColor='#F15622'
btntxtncolor="#ffffff"
btnMarginRight={imageWidth / 1000}
btnMarginLeft={imageWidth / 1000}
onPress={() => this.btnPress()} />
</TouchableOpacity>
<View style={{ paddingTop: wp('4%') }}>
<Text style={{ color: 'white', fontSize: wp('4%') }}>Don't have an account?
<TouchableOpacity onPress={() => this.props.navigation.navigate('VerificationSignUp')}>
<Text style={{ color: '#2793E1', fontWeight: 'bold', textDecorationLine: 'underline' }}>
Sign Up
</Text>
</TouchableOpacity>
</Text>
</View>
<View style={{ padding: wp('4%'), marginTop: hp('4%'), alignContent: 'center' }}>
<TouchableOpacity >
<Text style={{ color: 'white', fontSize: wp('3%') }}>By logging in you agree to the Spoton money
<TouchableOpacity onPress={() => this.clickPrivacypolicy()}>
<Text style={{ color: '#2793E1', fontSize: wp('3%'), paddingTop: wp('1%') }}>
Privacy policy .
</Text>
</TouchableOpacity>
and acknowledge our
<TouchableOpacity onPress={() => this.clickPrivacypolicy()}>
<Text style={{ color: '#2793E1', fontSize: wp('3%'), paddingTop: wp('1%') }}>
Terms & Conditions.
</Text>
</TouchableOpacity>
</Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
</View>
</ScrollView>
</SafeAreaView>
);
}
}
const mapStateToProps = state => {
return {
...state.startUpReducer
}
// loading: state.startUpReducer.loading,
// jwttoken: state.startUpReducer.jwttoken,
// customerDetailsAllResult: state.startUpReducer.customerDetailsAllResult,
// agentExposableId: state.startUpReducer.exposable_id
};
export default connect(mapStateToProps)(StartScreen);
const style = StyleSheet.create({
container: {
backgroundColor: '#343A4F',
height: wp()
}
})
redux/Actions.js
loginApp: (value) => ({
type: actions.LOGIN_SCREEN,
value
}),
redux/reducer.js
case startUpActions.LOGIN_SCREEN:
return{
...state,
loading:true
}
case startUpActions.LOGIN_SCREEN_RESULT:
return{
loading:false,
jwttoken:action.result.jwttoken
}
case startUpActions.LOGIN_SCREEN_ERROR:
return{
loading:false,
jwttoken:'errlogin'
}
redux/saga.js
export function* loginApp(){
yield takeEvery(actions.LOGIN_SCREEN, function* (payload) {
const requestBody=payload.value
const url = loginURL;
console.log(requestBody);
console.log(url);
try {
const response = yield fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(requestBody)
});
console.log(response)
const result = yield response.json();
console.log(result)
if (response.ok) {
yield put({ type: actions.LOGIN_SCREEN_RESULT, result });
} else {
yield put({
type: actions.LOGIN_SCREEN_ERROR,
result
});
}
} catch (error) {
yield put({ type: actions.LOGIN_SCREEN_ERROR });
}
});
}

Get user city from location coords data, in react native?

I got the coords but cannot get it to show the city. I almost got it. I even got the API key it requires but cannot do anything more. Please help me, I am going nuts. If you have any other way that I could do it, you can show it aswell it would be appreciated. Thank you. Here's what I could do so far:
import React from "react";
import { Button, PermissionsAndroid, SafeAreaView, StatusBar, StyleSheet, Text, View, Platform } from "react-native";
import GetLocation from 'react-native-get-location'
const locationToAdress = async(location) =>
{
const locationPublish = `${location.latitude},${location.longitude}`; //PUBLISH
const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${locationPublish}&sensor=true&key=${config.myGoogleAPIisaSecretnumber}`;
fetch(url)
.then((result) => {
const { results } = result;
console.log(results);
})
.catch((e) => {
console.log(e);
});
}
const requestLokasyonPermission = async () => {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
GetLocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 15000,
})
.then(location => {
console.log(location);
console.log(location.latitude);
console.log("lokasyon seysi bu" + location.longitude);
locationToAdress(location);
})
.catch(error => {
const { code, message } = error;
console.warn(code, message);
})
);
};
const requestCameraPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: "Cool Photo App Camera Permission",
message:
"Cool Photo App needs access to your camera " +
"so you can take awesome pictures.",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use the camera");
} else {
console.log("Camera permission denied");
}
} catch (err) {
console.warn(err);
}
};
const App = () => (
<View style={styles.container}>
<Text style={styles.item}>Try permissions</Text>
<Button title="request permissions" onPress={
() => { requestCameraPermission();}
}/>
<Text style={styles.item}>Try permissions</Text>
<Button title="request permissions" onPress={
() => { requestLokasyonPermission();}
}/>
</View>
);
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
paddingTop: StatusBar.currentHeight,
backgroundColor: "#ecf0f1",
padding: 8
},
item: {
margin: 24,
fontSize: 18,
fontWeight: "bold",
textAlign: "center"
}
});
export default App;
In locationToAdress you have used geocode service which converts address to latitude and longitude. In your case, you want the opposide - i.e. from latitude and longitude coordinates to address for which one should use reverse geocoding service as given here
I haven't worked on react-native-get-location, but you can refer below example for your code.
I am using react-native-geolocation-service.
Remove ${config.} before API Key
P.S. : Never Post Your Google Map API Key directly on any site.
import React from "react";
import { Button, PermissionsAndroid, SafeAreaView, StatusBar, StyleSheet, Text, View, Platform } from "react-native";
import Geolocation from 'react-native-geolocation-service'
const locationToAdress = async (location) => {
const locationPublish = `${location.latitude},${location.longitude}`; //PUBLISH
const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${locationPublish}&sensor=true&key=YOURGOOGLEMAPAPIKEY`;
fetch(url)
.then((result) => {
console.log(result);
})
.catch((e) => {
console.log(e);
});
}
const requestLokasyonPermission = async () => {
if (Platform.OS === "android") {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "Location Permission",
message:
"This App needs access to your location " +
"so we can know where you are.",
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use locations ");
} else {
console.log("Location permission denied");
}
} catch (err) {
console.warn(err);
}
}
Geolocation.getCurrentPosition(
(location) => {
console.log(location);
locationToAdress(location.coords)
},
(error) => {
console.log(error);
},
{ enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 }
);
};
const requestCameraPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: "Cool Photo App Camera Permission",
message:
"Cool Photo App needs access to your camera " +
"so you can take awesome pictures.",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use the camera");
} else {
console.log("Camera permission denied");
}
} catch (err) {
console.warn(err);
}
};
const App = () => (
<View style={styles.container}>
<Text style={styles.item}>Try permissions</Text>
<Button title="request permissions" onPress={
() => { requestCameraPermission(); }
} />
<Text style={styles.item}>Try permissions</Text>
<Button title="request permissions" onPress={
() => { requestLokasyonPermission(); }
} />
</View>
);
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
paddingTop: StatusBar.currentHeight,
backgroundColor: "#ecf0f1",
padding: 8
},
item: {
margin: 24,
fontSize: 18,
fontWeight: "bold",
textAlign: "center"
}
});
export default App;

Executing multiple functions OnPress

I'm trying to execute a function and navigate to the next screen using React-navigation and creating an Axios post
I've already tried combining both function's but It doesn't seem to execute the createOrder function
If I run the createOrder function alone it does work
onPress={
() => {
this.createOrder
this.props.navigation.navigate('Cart', {
order : this.state.order
});
}
}
import React from 'react';
import {
View,
StyleSheet,
Text,
Image,
TouchableOpacity
} from 'react-native';
//Redux
import { connect } from 'react-redux';
import { addItemToCart, removeItem } from '../../actions/ProductActionCreators';
//Products
import Products from '../../components/products/Products';
// Api Url
import ApiUrl from '../../helpers/ApiUrl'
//UI LIBRARY
import { Input, Button } from 'react-native-elements';
import {LinearGradient} from "../../components/LinearGradient";
import { ButtonGroup } from 'react-native-elements';
import Icon from "react-native-vector-icons/Ionicons";
//AXIOS
import axios from 'axios';
export class ProductsListView extends React.Component {
constructor(props) {
super(props);
const { rows } = this.props.navigation.state.params;
const arrays = Object.values( {rows});
this.state = {
arrays,
filteredProducts: arrays,
selectedIndex: 2
};
this.updateIndex = this.updateIndex.bind(this)
}
createOrder () {
axios.post( ApiUrl + 'api/order/post', {
code: "4f",
status: "waiting",
user_name: "salman",
user_id: 1,
club_id: 1,
})
.then(response => {
this.setState({
order: response.data,
});
console.log('created order',this.state.order)
})
.catch(function (error) {
console.log('error',error);
})
}
updateIndex (selectedIndex) {
this.setState({selectedIndex})
}
filterAll(){
}
filterStrong(){
this.setState({
arrays: this.state.arrays[0].products.filter(item => item.type == "strong" )
})
console.log(this.state.arrays)
}
filterNormal(){
}
render() {
const component1 = () => <Icon
name="ios-star"
size={15}
color="gold"
/>
const component2 = () => <Icon
name="ios-beer"
size={15}
color="gold"
onPress={() => this.filterStrong}
/>
const component3 = () => <Icon
name="ios-wine"
size={15}
color="gold"
/>
const buttons = [{ element: component1 }, { element: component2 }, { element: component3 }]
const { selectedIndex } = this.state
return (
<View style={styles.container} >
<Image
style={styles.imageCard}
source={
{
uri:
this.state.arrays[0].image
}
}
/>
<Text style={styles.title} >
{this.state.arrays[0].name}
</Text>
<Products
products={this.state.arrays[0].products}
addItemToCart={this.props.addItemToCart}
removeItem={this.props.removeItem}
/>
<View style={{
justifyContent:'center',
width: '100%',
padding: 50,
paddingTop:20,
}}>
<Button
title="Go to my cart"
containerStyle={{ flex: -1 }}
buttonStyle={styles.signUpButton}
linearGradientProps={{
colors: ['#dd016b', '#dd016b'],
start: [1, 0],
end: [0.2, 0],
}}
ViewComponent={LinearGradient}
titleStyle={styles.signUpButtonText}
// onPress={this.createOrder}
onPress={
() => {
this.createOrder
this.props.navigation.navigate('Cart', {order : this.state.order});
}
}
/>
</View>
</View>
)
}
}
const mapDispatchToProps = {
addItemToCart,
removeItem
}
export default connect(null, mapDispatchToProps) (ProductsListView);
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
width:'100%',
backgroundColor: 'black',
},
signUpButtonText: {
// fontFamily: 'bold',
fontSize: 13,
},
signUpButton: {
width: 250,
borderRadius: 50,
height: 45,
},
title: {
color:'white',
fontSize:32,
height: 100,
position: 'relative',
backgroundColor: '#00000054',
width: "100%",
textAlign: 'center',
paddingTop: 30,
},
imageCard:{
height:100,
width:'100%',
position: "absolute",
top: 0,
backgroundColor: 'white'
},
button: {
padding: 5,
borderRadius: 25,
margin: 5,
backgroundColor: '#DD016B',
color: 'white',
alignItems: 'center',
justifyContent: 'center',
},
})
I'm trying to navigate to the next screen with the data from I get from my Axios post.
You are not calling the createOrder function.
Try this:
<Button
title="Go to my cart"
containerStyle={{ flex: -1 }}
buttonStyle={styles.signUpButton}
linearGradientProps={{
colors: ["#dd016b", "#dd016b"],
start: [1, 0],
end: [0.2, 0]
}}
ViewComponent={LinearGradient}
titleStyle={styles.signUpButtonText}
// onPress={this.createOrder}
onPress={this.onGoToMyCartPressed}
/>;
And onGoToMyCartPressed would look like:
onGoToMyCartPressed = () => {
this.createOrder(); // <- Call the function
this.props.navigation.navigate("Cart", { order: this.state.order });
};
And, if you want to navigate after the order has been created, then, have your createOrder return the promise, and you can chain off of it in the onGoToMyCartPressed
Like so:
createOrder() {
// Return the promise from here
return axios.post( ApiUrl + 'api/order/post', {
code: "4f",
status: "waiting",
user_name: "salman",
user_id: 1,
club_id: 1,
}).then(response => {
this.setState({
order: response.data,
});
console.log('created order',this.state.order)
}).catch(function (error) {
console.log('error',error);
})
}
And modify the onGoToMyCartPressed to use the promise returned.
onGoToMyCartPressed = () => {
// CHange the page once the order has been craeted
this.createOrder().then(() => {
this.props.navigation.navigate("Cart", { order: this.state.order });
})
};

React - Value from API doesn't appear in View

I'm very new to React Native and following a course where I meet this issue :
This component shows "TEXT" but doesn't show {film.title}
_displayFilm() {
const { film } = this.state
if (film != undefined) {
return (
<ScrollView style={styles.scrollview_container}>
<Text>TEXT</Text>
<Text>{film.title}</Text>
</ScrollView>
)
}
}
I'm Using Atom in Ubuntu and use Expo Android App to see the result.
Another inconvenient I have is that I don't get logs from console.log() in Atom terminal that could have helped me for example to see complete json film object.
The value "title is correct (use in another page of my app).
If anybody have an idea how to solve it, thanks a lot !
If useful, here is the complete file content :
// Components/FilmDetail.js
import React from 'react'
import { StyleSheet, View, Text, ActivityIndicator, ScrollView, Image } from 'react-native'
import { getFilmDetailFromApi, getImageFromApi } from '../API/TMDBApi'
import moment from 'moment'
import numeral from 'numeral'
class FilmDetail extends React.Component {
constructor(props) {
super(props)
this.state = {
film: undefined,
isLoading: true
}
}
componentDidMount() {
getFilmDetailFromApi(this.props.navigation.state.params.idFilm).then(data => {
this.setState({
film: data,
isLoading: false
})
})
}
_displayLoading() {
if (this.state.isLoading) {
return (
<View style={styles.loading_container}>
<ActivityIndicator size='large' />
</View>
)
}
}
_displayFilm() {
const { film } = this.state
if (film != undefined) {
return (
<ScrollView style={styles.scrollview_container}>
<Text>TEXT</Text>
<Text>{film.title}</Text>
<Text style={styles.title_text}>{film.release_date}</Text>
<Text style={styles.title_text}>{film.backdrop_path}</Text>
</ScrollView>
)
}
}
render() {
return (
<View style={styles.main_container}>
{this._displayLoading()}
{this._displayFilm()}
</View>
)
}
}
const styles = StyleSheet.create({
main_container: {
flex: 1
},
loading_container: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
},
scrollview_container: {
flex: 1
},
image: {
height: 169,
margin: 5
},
title_text: {
fontWeight: 'bold',
fontSize: 35,
flex: 1,
flexWrap: 'wrap',
marginLeft: 5,
marginRight: 5,
marginTop: 10,
marginBottom: 10,
color: '#000000',
textAlign: 'center'
},
description_text: {
fontStyle: 'italic',
color: '#666666',
margin: 5,
marginBottom: 15
},
default_text: {
marginLeft: 5,
marginRight: 5,
marginTop: 5,
}
})
export default FilmDetail
And the called API is here :
const API_TOKEN = "MY_API_TOKEN"
export function getFilmsFromApiWithSearchedText (text, page) {
const url = 'https://api.themoviedb.org/3/search/movie?api_key=' + API_TOKEN + '&language=fr&query=' + text + "&page=" + page
return fetch(url)
.then((response) => response.json())
.catch((error) => console.error(error))
}
export function getImageFromApi(name) {
return 'https://image.tmdb.org/t/p/w185' + name
}
export function getFilmDetailFromApi(id) {
const url = 'https://api.themoviedb.org/3/movie/' + id + 'api_key=' + API_TOKEN + '&language=fr'
return fetch(url)
.then((response) => response.json())
.catch((error) => console.log(error))
}
I think you are missing a ? in before the api_key:
const url = 'https://api.themoviedb.org/3/movie/' + id + '?api_key=' + API_TOKEN + '&language=fr'
you need to fix the console, as it must be showing that the response is wrong in the console atm... HTH
I believe your apiFunction should be more like this:
export function getFilmDetailFromApi(id) {
const url = 'https://api.themoviedb.org/3/movie/' + id + '?api_key=' + API_TOKEN + '&language=fr'
return fetch(url)
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => console.log(error))
}
Try this in your component:
this.state = {
film: {}, //change the undefined
isLoading: true
}
componentDidMount() {
this.getMovie();
}
getMovie() {
const movie = getFilmDetailFromApi(this.props.navigation.state.params.idFilm);
if (movie.hasOwnProperty('id')) { //that means a movie was returned
this.setState({ film: movie, isLoading: false });
}
}
The text in _displayFilm is showing because you have already set film as undefined. So as long as the state doesn't change, the text will show.
Change your _displayFilm:
_displayFilm() {
const { film } = this.state
if (film.hasOwnProperty('id')) {
return (
<ScrollView style={styles.scrollview_container}>
<Text>TEXT</Text>
<Text>{film.title}</Text>
<Text style={styles.title_text}>{film.release_date}</Text>
<Text style={styles.title_text}>{film.backdrop_path}</Text>
</ScrollView>
)
}
}
Now the problem might be that you are not getting the right data. It is possible that your data is contained in response.data.data or response.data and not just in response. So by all means console.log(response) and inspect

Resources