have Request failed with status code 400 error in react native - reactjs

I am using Axios to get data from JSON files and I tried it in postman it works, also the app works but sometimes when I open the app this error appears: Request failed with status code 400 and data disappears can you help solve. am I fetching data in the wrong way?
if there another way to avoid this error please mention it
here is my code:
`
import { StyleSheet, Text, View, Image, ScrollView, TouchableOpacity, TextInput, Pressable, Dimensions } from 'react-native'
import React, { useEffect, useState } from 'react'
import { useNavigation, useRoute } from "#react-navigation/native";
import axios from 'axios';
import LottieView from 'lottie-react-native';
import { Rating } from 'react-native-stock-star-rating'
import { AntDesign } from '#expo/vector-icons';
const LoadingDirection = () => {
return (
<LottieView
ref={animation => {
animation = animation
}}
style={{
width: 210,
height: 210,
alignSelf: 'center'
}}
source={require('../../assets/gif/loading.json')}
autoPlay
loop
/>
)
}
const ArtistSearch = () => {
const route = useRoute()
let token = route.params.token
const navigation = useNavigation();
const [artist, setArtist] = useState([]);
const [loaded, setLoaded] = useState(false);
const [search, setSearch] = useState('');
const [masterData, setMasterData] = useState([]);
const [empty, SetEmpty] = useState(false)
const ArtistData = async () => {
const resp = await axios.get('https://api.spotify.com/v1/search?query=remaster%2520track%3ADoxy%2520artist%3AMiles%2520Davis&type=artist&market=ES&locale=en-US%2Cen%3Bq%3D0.9&offset=5&limit=10', {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
})
return resp.data.artists.items;
};
useEffect(() => {
ArtistData().then(artists => {
setArtist(artists)
setMasterData(artists)
setLoaded(true);
}).catch(err => {
console.log(err)
});
}, []);
return (
<ScrollView>
<View style={{ alignItems: 'center', marginTop: 20 }}>
<Pressable>
<View style={styles.searchSection}>
<TextInput
style={styles.input}
placeholder="Search for an artist..."
underlineColorAndroid="transparent"
value={search}
/>
<AntDesign name="search1" size={24} color="Black" />
</View>
</Pressable>
</View>
{artist.map((data, i) => (
<TouchableOpacity onPress={() => { navigation.navigate('AlbumScreen',{artistId:data.id,token:token,artistName:data.name}) }} key={i}>
<View>
<View style={styles.paper}>
<Image source={{ uri: data.images.url }} style={{ height: 350, width: Dimensions.get('window').width - 40, resizeMode: 'cover' }} />
<View style={{ height: 1, width: Dimensions.get('window').width - 40, backgroundColor: 'gray', marginBottom: 10 }}></View>
<Text style={{ paddingLeft: 10, fontSize: 24, fontWeight: '600' }}>{data.name}</Text>
<Text style={{ color: 'gray', marginLeft: 10, marginBottom: 10 }}>{data.followers.total} followers</Text>
<View style={{ marginLeft: 10 }}>
<Rating stars={data.popularity / 2} maxStars={5} size={25} />
</View>
<View style={{ marginBottom: 20 }} />
</View>
</View>
</TouchableOpacity>
))}
{!loaded && LoadingDirection()}
</ScrollView>
)
}
export default ArtistSearch
const styles = StyleSheet.create({
paper: {
width: Dimensions.get('window').width - 40,
backgroundColor: 'white',
shadowColor: 'black',
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.002,
shadowRadius: 22,
elevation: 3,
margin: 8,
marginTop: 20,
marginLeft: 20,
marginRight: 20,
borderColor: 'gray',
borderWidth: 0.2
},
heading: {
fontSize: 17,
marginBottom: 5,
marginLeft: 10,
marginTop: 10
},
stars: {
display: 'flex',
flexDirection: 'row',
marginLeft: 10, marginBottom: 20
},
starUnselected: {
color: '#aaa',
},
starSelected: {
color: '#ffb300',
},
searchSection: {
width: Dimensions.get('window').width - 40,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
borderColor: 'Black',
borderWidth: 1,
borderRadius: 10,
paddingHorizontal: 10
},
searchIcon: {
padding: 10,
},
input: {
flex: 1,
paddingTop: 10,
paddingRight: 10,
paddingBottom: 10
},
})
`

Related

How to Not change to initial state when other state change their value

Hello there I am phasing an logic issue where I don't want my other useState render(run) whenever another state change their value because it render full component every time so it initialize default values.
here when useEffect run and it change item value by setitem but after component run again so it initialize default again
import React, { useState, useEffect, useRef, useLayoutEffect } from "react";
import {
Image,
StyleSheet,
TouchableOpacity,
Text,
View,
SafeAreaView,
FlatList,
TextInput,
} from "react-native";
import { EvilIcons } from "#expo/vector-icons";
import { MaterialCommunityIcons, Ionicons } from "#expo/vector-icons";
import axios from "axios";
import { AsyncStorage } from "react-native";
import url from "../url";
const Handlenewspost = ({ navigation }) => {
var items = navigation.getParam("item");
var user = navigation.getParam("user");
var functionforoffset = navigation.getParam("functionforoffset");
const [item, setitem] = useState(items);
var like = item.like;
var found = like.find((element) => {
if (element.username === user.username) return true;
});
found ? (item.userlike = true) : false;
var checklike = "";
item.userlike ? (checklike = "heart") : (checklike = "heart-outline");
item.userlike ? (checkcolor = "red") : (checkcolor = "black");
const [likebutton, setlikebutton] = useState(checklike);
const [postlikes, setpostlikes] = useState(item.likes);
const [likebuttoncolor, setlikebuttoncolor] = useState(checkcolor);
useEffect(() => {
axios
.get(url + "post/byid/" + items._id)
.then((response) => {
setitem(response.data);
})
.catch((err) => {
console.log(err);
console.log(err.response.data.error);
Alert.alert("Something went wrong", err.response.data.error, [
{ text: "OK", onPress: () => console.log("OK Pressed") },
]);
});
}, []);
const onpresshandle = async (item) => {
userToken = await AsyncStorage.getItem("userToken");
id = item._id;
token = userToken;
functionforoffset();
axios
.post(url + "post/like", { token, id })
.then((response) => {
if (!response.data) {
} else {
}
})
.catch((err) => {
console.log(err);
console.log(err.response.data.error);
Alert.alert("Something went wrong", err.response.data.error, [
{ text: "OK", onPress: () => console.log("OK Pressed") },
]);
});
};
function checkcaption(caption) {
if (caption != "") {
return (
<SafeAreaView style={styles.safe}>
<View
style={[
styles.root,
{ flexDirection: "row", alignItems: "center" },
]}
>
<Text style={[styles.textStyle, { fontSize: 15, marginLeft: 0 }]}>
{item.caption}
</Text>
</View>
</SafeAreaView>
);
} else {
return <View></View>;
}
}
return (
<>
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.container}>
<View style={styles.card}>
<View style={styles.cardheader}>
{item.profileimage ? (
<Image
source={{ uri: url + "filename/" + item.profileimage }}
style={{
marginLeft: 16,
marginRight: 8,
height: 40,
width: 40,
borderRadius: 100,
}}
></Image>
) : (
<Image
source={require("../../assets/localbazilogo2.jpeg")}
style={[
styles.profileimage,
{ marginLeft: 16, marginRight: 5 },
]}
></Image>
)}
<Text style={{ fontWeight: "bold", fontSize: 15, marginLeft: 5 }}>
{item.username}
</Text>
</View>
<View style={styles.cardbody}>
{item.filename ? (
<Image
style={styles.cardbodyimage}
resizeMode="stretch"
source={{ uri: url + "filename/" + item.filename }}
></Image>
) : (
<View></View>
)}
</View>
<View style={styles.cardfooter}>
<MaterialCommunityIcons
onPress={() => {
if (item.userlike) {
setlikebutton("heart-outline");
setlikebuttoncolor("black");
setpostlikes(postlikes - 1);
} else {
setlikebutton("heart");
setlikebuttoncolor("red");
setpostlikes(postlikes + 1);
}
item.userlike = !item.userlike;
onpresshandle(item);
}}
name={likebutton}
size={28}
color={likebuttoncolor}
style={{ marginLeft: 10, marginTop: 4 }}
>
{" "}
</MaterialCommunityIcons>
<Text style={{ fontSize: 18, marginLeft: 1 }}>{postlikes}</Text>
<EvilIcons
name="comment"
size={30}
style={{ marginLeft: 20, marginTop: 4 }}
color="black"
/>
<Image
style={{ marginLeft: 20, marginTop: 4 }}
source={require("../../assets/share.png")}
></Image>
</View>
{checkcaption(item.caption)}
<View style={styles.showcomment}>
<Text>
View all {item.comments ? item.comments.length : 0} comments
</Text>
</View>
<View style={styles.comment}>
<View>
{user.profileimage ? (
<Image
source={{ uri: url + "filename/" + user.profileimage }}
style={{
height: 35,
width: 35,
borderRadius: 100,
marginLeft: 14,
}}
></Image>
) : (
<View></View>
)}
</View>
<View style={styles.addcomment}>
<Text
style={{
marginHorizontal: 5,
fontSize: 14,
color: "#9CA3AF",
width: 240,
}}
>
Add Comment
</Text>
</View>
</View>
</View>
</View>
</SafeAreaView>
</>
);
};
export default Handlenewspost;
const styles = StyleSheet.create({
showcomment: { marginLeft: 20, marginBottom: 5 },
addcomment: {
overflow: "hidden",
marginLeft: 20,
marginRight: 20,
padding: 7,
backgroundColor: "#E6E7E9",
borderRadius: 25,
},
comment: {
marginTop: 10,
flexDirection: "row",
alignItems: "center",
},
email: {
flexDirection: "row",
overflow: "hidden",
marginLeft: 20,
marginRight: 20,
marginTop: 10,
marginBottom: 20,
padding: 7,
backgroundColor: "#E6E7E9",
borderRadius: 25,
},
iconout: { width: "20%", alignItems: "center" },
icon: { height: 35, width: 35, resizeMode: "stretch" },
icons: {
flexDirection: "row",
flexWrap: "wrap",
marginTop: 1,
marginHorizontal: 28,
marginBottom: 20,
},
profileimage: {
width: "12%",
height: "170%",
borderRadius: 100,
resizeMode: "stretch",
},
safe: {
flex: 1,
marginTop: -10,
},
root: {
flex: 1,
padding: 16,
},
textStyle: {
fontSize: 14,
},
container: {
justifyContent: "center",
flex: 1,
},
cardfooter: {
flexDirection: "row",
alignItems: "center",
},
cardbodyimage: {
height: 350,
width: "100%",
marginTop: 3,
borderRadius: 3,
},
cardbody: {},
cardheader: {
flexDirection: "row",
alignItems: "center",
marginVertical: 12,
},
card: {
marginVertical: 10,
marginHorizontal: 4,
},
});

Centering content in the middle of the screen in a react native application

i want to center my view at the center of the screen but its unable am using justifyContent: 'center',
alignItems: 'center', but its all unable to put the contents at the middle of the screen i want the content to go to middle of the screen
i want the buttons and the inputs all to be at the middle of the screen .
i have tried to align but its unable to
import React, {useState, useEffect, useContext} from 'react';
import UserContext from './useContextStore';
import {
Text,
View,
Button,
TextInput,
StyleSheet,
TouchableOpacity,
Platform,
} from 'react-native';
import AsyncStorage from '#react-native-async-storage/async-storage';
import auth from '#react-native-firebase/auth';
import DataViewDoc from './view';
const PhoneInput = ({navigation}) => {
const [number, setNumber] = useState({number: ''});
const [value, loadedVal] = useState({value: true});
const [screenDaetail, setScreenDaetail] = useState(true);
const [waiting, setwaiting] = useState(false);
const [code, setCode] = useState({code: '', number: ''});
const [confirm, setConfirm] = useState(null);
const [codee, setCodee] = useState('');
// let num;
const getNumber = (val) => {
setNumber({number: val});
};
const getCode = (val) => {
setCode({code: val, number: number.number});
};
//firebase**************************************************************************
async function signInWithPhoneNumber(phoneNumber) {
const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
console.log('confirmation code is ', confirmation);
setConfirm(confirmation);
}
async function confirmCode() {
try {
await confirm.confirm(codee).then(() => {
console.log('logged in');
// setScreenDaetail(!screenDaetail);
navigation.navigate('codeForma');
});
} catch (error) {
console.log('Invalid code.');
}
}
return (
<View styles={style.container}>
{confirm ? (
<>
<View styles={style.content}>
<Text style={style.TextStyle1}>Enter Valid Code </Text>
</View>
<View style={style.viewForText}>
<TextInput
style={style.textinput}
onChangeText={(text) => setCodee(text)}
secureTextEntry={true}
maxLength={13}
value={codee}
/>
</View>
<View style={style.viewForSend}>
<TouchableOpacity
style={style.SubmitButtonStyle}
activeOpacity={0.1}
onPress={() => {
// sendPhoneCodeTwillio();
confirmCode();
}}>
<Text style={style.TextStyle}> SEND</Text>
</TouchableOpacity>
<TouchableOpacity
style={style.SubmitButtonStyle2}
activeOpacity={0.1}
onPress={() => {
// sendPhoneTwilio();
setConfirm(null);
}}>
<Text style={style.TextStyle}> Back </Text>
</TouchableOpacity>
</View>
</>
) : (
<>
<View styles={style.content}>
<Text style={style.TextStyle1}>Enter Phone number </Text>
</View>
<View style={style.viewForText}>
<TextInput
style={style.textinput}
onChangeText={(text) => {
getNumber(text);
}}
maxLength={13}
value={number.number}
/>
</View>
<View style={style.viewForSend}>
<TouchableOpacity
style={style.SubmitButtonStyle}
activeOpacity={0.1}
onPress={() => {
signInWithPhoneNumber(number.number);
}}>
<Text style={style.TextStyle}> SEND </Text>
</TouchableOpacity>
<TouchableOpacity
style={style.SubmitButtonStyle2}
activeOpacity={0.1}
onPress={() => {
signInWithPhoneNumber(number.number);
}}>
<Text style={style.TextStyle}> RESEND </Text>
</TouchableOpacity>
</View>
</>
)}
</View>
);
};
const style = StyleSheet.create({
container: {
flex: 1,
// paddingBottom: Platform.OS === 'android' ? 50 : 0,
justifyContent: 'center',
alignItems: 'center',
},
textinput: {
margin: 25,
borderColor: '#7a42f4',
borderWidth: 5,
borderRadius: 35,
color: 'black',
textAlign: 'center',
fontFamily: 'Cochin',
fontSize: 20,
fontWeight: 'bold',
},
viewForText: {width: 250, alignSelf: 'center'},
viewForSend: {
width: 400,
// alignSelf: 'baseline',
borderRadius: 20,
margin: 10,
flexDirection: 'row',
justifyContent: 'center',
alignSelf: 'center',
},
content: {
// justifyContent: 'center',
// // alignItems: 'flex-start',
flex: 2,
justifyContent: 'flex-end',
marginBottom: 36,
},
topTierblack: {
backgroundColor: 'black',
borderRadius: 100,
width: 300,
marginLeft: 40,
opacity: 0.5,
},
topTierRed: {
backgroundColor: 'red',
borderRadius: 100,
width: 300,
marginLeft: 40,
},
topTierGreen: {
backgroundColor: 'green',
borderRadius: 100,
width: 300,
marginLeft: 40,
opacity: 0.5,
},
viewForSend2: {
width: 200,
alignSelf: 'flex-end',
borderRadius: 20,
// margin: 10,
},
buttonContainer: {
width: '40%',
alignSelf: 'center',
marginVertical: 30,
color: 'red',
borderRadius: 10,
},
SubmitButtonStyle: {
marginTop: 10,
paddingTop: 15,
paddingBottom: 15,
marginLeft: 30,
marginRight: 30,
backgroundColor: '#00BCD4',
borderRadius: 10,
borderWidth: 1,
borderColor: '#fff',
shadowOpacity: 0.5,
shadowColor: 'blue',
height: 50,
width: 100,
},
SubmitButtonStyle2: {
marginTop: 10,
paddingTop: 15,
paddingBottom: 15,
marginLeft: 30,
marginRight: 30,
backgroundColor: 'black',
borderRadius: 10,
borderWidth: 1,
borderColor: '#fff',
shadowOpacity: 0.5,
shadowColor: 'blue',
height: 50,
width: 100,
},
TextStyle: {
color: '#fff',
textAlign: 'center',
},
TextStyle1: {
color: 'black',
textAlign: 'center',
fontFamily: 'Cochin',
fontSize: 20,
fontWeight: 'bold',
},
});
export default PhoneInput;
Remove the marginRight from SubmitButtonStyle and the marginLeft from SubmitButtonStyle2 and you should be fine.

How to move down a object using button in react native?

Actually I want to do something like that (Image attached):
There have a box, and two buttons. If I press button 1 then the box moved left. And if I press button 2 then the box moved right.
I want, when the box move right and overcome the bar 1 then the box moved down on the bar 2.
But I have no idea how to do it.
Here is my code:
import React, {Component} from 'react';
import {
View,
Text,
StyleSheet,
Animated,
TouchableOpacity,
ScrollView,
Image,
} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
left: 20,
};
}
moveRight = () => {
this.setState({left: this.state.left + 10}); // 10 is value of change.
};
moveLeft = () => {
this.setState({left: this.state.left - 10}); // 10 is value of change.
};
render() {
return (
<View style={styles.container}>
<Image
style={{left: this.state.left, height: 120, width: 120}}
source={require('./assets/box.png')}
/>
<Image
style={{height: 20, width: 180, marginTop: -12, marginLeft: 25}}
source={require('./assets/log.png')}
/>
<Image
style={{height: 20, width: 200, marginTop: 150, marginLeft: 185}}
source={require('./assets/log.png')}
/>
<View style={styles.buttonsContainer}>
<TouchableOpacity onPress={this.moveLeft}>
<Image
style={{height: 60, width: 60}}
source={require('./assets/left-button.png')}
/>
</TouchableOpacity>
<TouchableOpacity onPress={this.moveRight}>
<Image
style={{height: 60, width: 60}}
source={require('./assets/right-button.png')}
/>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
textCenter: {
alignSelf: 'center',
textAlign: 'center',
},
levelHeading: {
fontWeight: 'bold',
fontSize: 35,
color: '#CC8A4F',
},
buttonsContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 200,
paddingLeft: 80,
paddingRight: 80,
},
});
Please help me!
Thanks!
import React, { useEffect } from "react";
import { Animated, Text, View, StyleSheet, Button } from "react-native";
const App = () => {
const moveAnimation = new Animated.ValueXY({ x: 10, y: 450 });
useEffect(() => {
moveAnimation;
}, []);
const _moveBallLeft = () => {
Animated.spring(moveAnimation, {
toValue: { x: 250, y: 450 },
}).start();
};
const _moveBallRight = () => {
Animated.spring(moveAnimation, {
toValue: { x: 10, y: 450 },
}).start();
};
return (
<View style={styles.container}>
<Animated.View style={[styles.tennisBall, moveAnimation.getLayout()]}>
<View style={styles.button}>
<Text style={styles.buttonText}>ball</Text>
</View>
</Animated.View>
<View
style={{
flexDirection: "row-reverse",
justifyContent: "space-evenly",
}}
>
<View style={{ alignSelf: "center" }}>
<Button title=">" onPress={_moveBallLeft}></Button>
</View>
<View style={{ alignSelf: "center", marginLeft: "2%" }}>
<Button title="<" onPress={_moveBallRight}></Button>
</View>
</View>
</View>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex: 2,
backgroundColor: "#ecf0f1",
},
tennisBall: {
display: "flex",
justifyContent: "center",
alignItems: "center",
backgroundColor: "greenyellow",
borderRadius: 100,
width: 100,
height: 100,
},
button: {
paddingTop: 24,
paddingBottom: 24,
},
buttonText: {
fontSize: 24,
color: "#333",
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

TypeError: undefined is not an object (evaluating 'navigation.route.params')

This is the Screen 1(LoginScreen.js) code where we fetch the Data from an API, which responses in JSON format, where we will get 'custRegId', 'email', 'firstName', 'lastName' & 'mobileNumber'.
import {
StyleSheet, TextInput, View, Text, ScrollView, Image, Keyboard, Button,
TouchableOpacity, KeyboardAvoidingView, ActivityIndicator} from 'react-native';
import AsyncStorage from '#react-native-community/async-storage';
import Loader from './Components/loader';
import axios from 'axios';
import HomeScreen from './drawerScreens/HomeScreen';
const LoginScreen = props => {
let [userEmail, setUserEmail] = useState('');
let [userPassword, setUserPassword] = useState('');
let [loading, setLoading] = useState(false);
let [errortext, setErrortext] = useState('');
let [name, setName1] = useState('');
let [item, setItem] = useState('');
let [custRegId, setCustRegId] = useState('');
const handleSubmitPress = () => {
global.myUrl = 'Default API URL';
setErrortext('');
if (!userEmail) {
alert('Please fill Email');
return;
}
if (!userPassword) {
alert('Please fill Password');
return;
}
setLoading(true);
var dataToSend = { email: userEmail, password: userPassword };
var formBody = [];
for (var key in dataToSend) {
var encodedKey = encodeURIComponent(key);
var encodedValue = encodeURIComponent(dataToSend[key]);
formBody.push(encodedKey + '=' + encodedValue);
}
formBody = formBody.join('&');
let data = {
email: userEmail,
password: userPassword
}
console.log(data.firstName)
axios.post(myUrl, data, { withCredentials: true })
.then(response => {console.log(response.data, "Logged in Successfully")
.then((json) => {props.navigation.navigate('HomeScreen')})
.catch(error => {
setLoading(false);
console.error("Incorrect Credentials");
});
console.log(setName1);
});
return (
<View style={styles.mainBody}>
<Loader loading={loading} />
<ScrollView keyboardShouldPersistTaps="handled">
<View style={{ marginTop: 100 }}>
<KeyboardAvoidingView enabled>
<View style={{ alignItems: 'center' }}>
<Image
source={require('../Image/aboutreact.png')}
style={{
width: '90%',
height: 80,
resizeMode: 'contain',
margin: 30,
}}
/>
</View>
<View style={styles.SectionStyle}>
<TextInput
style={styles.inputStyle}
onChangeText={UserEmail => setUserEmail(UserEmail)}
placeholder="Enter Email"
placeholderTextColor="#FFFFFF"
autoCapitalize="none"
keyboardType="email-address"
ref={ref => {
this._emailinput = ref;
}}
returnKeyType="next"
onSubmitEditing={() =>
this._passwordinput && this._passwordinput.focus()
}
blurOnSubmit={false}
/>
</View>
<View style={styles.SectionStyle}>
<TextInput
style={styles.inputStyle}
onChangeText={UserPassword => setUserPassword(UserPassword)}
placeholder="Enter Password"
placeholderTextColor="#FFFFFF"
keyboardType="default"
ref={ref => {
this._passwordinput = ref;
}}
onSubmitEditing={Keyboard.dismiss}
blurOnSubmit={false}
secureTextEntry={true}
/>
</View>
{errortext != '' ? (
<Text style={styles.errorTextStyle}> {errortext} </Text>
) : null}
<TouchableOpacity
style={styles.buttonStyle}
activeOpacity={0.5}>
<Text style={styles.buttonTextStyle}
onPress={handleSubmitPress}>LOGIN</Text>
</TouchableOpacity>
<Text style={styles.registerTextStyle}>Don't have an account yet?</Text>
<Text
style={styles.registerTextStyle1}
onPress={() => props.navigation.navigate('RegisterScreen')}>
Register Here
</Text>
</KeyboardAvoidingView>
</View>
</ScrollView>
</View>
);
};
export default LoginScreen;
const styles = StyleSheet.create({
mainBody: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#455a64',
},
SectionStyle: {
flexDirection: 'row',
height: 40,
marginTop: 20,
marginLeft: 35,
marginRight: 35,
margin: 10,
},
buttonStyle: {
backgroundColor: '#5D6D7E',
borderWidth: 0,
color: '#FFFFFF',
borderColor: '#7DE24E',
height: 40,
alignItems: 'center',
borderRadius: 30,
marginLeft: 35,
marginRight: 35,
marginTop: 20,
marginBottom: 20,
},
buttonTextStyle: {
color: '#FFFFFF',
paddingVertical: 10,
fontSize: 16,
},
inputStyle: {
flex: 1,
width:300,
backgroundColor: 'rgba(255, 255, 255, 0.3)',
paddingLeft: 25,
paddingRight: 15,
borderWidth: 1,
borderRadius: 30,
borderColor: 'white',
fontSize: 16
},
registerTextStyle: {
color: '#FFFFFF',
textAlign: 'center',
fontWeight: 'bold',
fontSize: 15,
},
errorTextStyle: {
color: 'red',
textAlign: 'center',
fontSize: 14,
},
registerTextStyle1: {
color: '#4493DC',
textAlign: 'center',
fontSize:14,
fontWeight: 'bold'
}
});}
This is Screen 2(HomeScreen.js) code where we need to get Data from Screen 1, where we need to display 'firstName' & 'lastName' as "Welcome, Abdul Kalam!".
import { View, Text } from 'react-native';
import axios from 'axios';
const HomeScreen = (props) => {
global.currentScreenIndex = 'HomeScreen';
return (
<View style={{ flex: 1, alignItems: 'center', marginTop: 100 }}>
<Text style={{ fontSize: 23, marginTop: 10 }}>Welcome, </Text>
</View>
);
};
export default HomeScreen;
I'm getting an error as :
-->TypeError: undefined is not an object (evaluating 'navigation.route.params')
-->Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

how to detect a face with react-native-camera facedetector?

I am trying to detect face with react-native-camera, I want to know how can we detect an individual's face, there is no proper documentation about the mlkit.
await FaceDetector.detectFacesAsync(data.uri) this statement is just returning face object like this face[0] = { bounds: { origin: { x: 739, y: 987 }, size: { x: 806, y: 789 } }, faceID: 0, rollAngle: 10.533509254455566, yawAngle: 0.7682874798774719 }.
This is just object's position, I cannot figure out how to recognize individual's face characteristics like eys, nose with the FaceDetector and suppose I will save person A's face data then how I will match the data with A's face later with react-native-camera ?
ML Kit does not support Face Recognition. Also, React Native is not officially supported (yet), but you could check out https://rnfirebase.io/ml-vision/face-detection#process which outlines how you can get a 133-point contour of the face. However, this is not meant for facial recognition, but rather for overlays (e.g. masks, filters).
import SplashScreen from 'react-native-splash-screen'
import React, { useEffect, createRef,useState } from 'react';
import { SafeAreaView, View, Image, StyleSheet, Text, Modal, TouchableOpacity } from 'react-native';
import { RNCamera } from 'react-native-camera';
const Test = (props) => {
useEffect(() => {
SplashScreen.hide();
});
const [faces, setFace] = useState([]);
const [faceavl, setFaceavl] = useState(false);
const [takeTimeFaceAvl, setTakeTimeFaceAvl] = useState(false);
const [searchWaiting, setsearchWaiting] = useState(null)
const [modalVisible, setModalVisible] = useState(false);
const [image, setImage] = useState(null);
const mycamera = createRef()
const PendingView = () => (
<View
style={{
flex: 1,
backgroundColor: 'lightgreen',
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text>Waiting</Text>
</View>
);
const renderFaces = () => (
<View style={{
position: 'absolute',
bottom: 0,
right: 0,
left: 0,
top: 0,
}} pointerEvents="none">
{faces.map(renderFace)}
</View>
);
const renderFace = ({ bounds, faceID, rollAngle, yawAngle }) => (
<View
key={faceID}
transform={[
{ perspective: 600 },
{ rotateZ: `${rollAngle.toFixed(0)}deg` },
{ rotateY: `${yawAngle.toFixed(0)}deg` },
]}
style={[
{
padding: 10,
borderWidth: 1,
borderRadius: 2,
position: 'absolute',
borderColor: '#000',
justifyContent: 'center',
},
{
...bounds.size,
left: bounds.origin.x,
top: bounds.origin.y,
},
]}
>
</View>
);
return (
<>
<SafeAreaView style={styles.container}>
<RNCamera
ref={mycamera}
style={styles.preview}
type={RNCamera.Constants.Type.front}
flashMode={RNCamera.Constants.FlashMode.on}
androidCameraPermissionOptions={{
title: 'Permission to use camera',
message: 'We need your permission to use your camera',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
androidRecordAudioPermissionOptions={{
title: 'Permission to use audio recording',
message: 'We need your permission to use your audio',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
onFacesDetected={(data) => {
setFace(data.faces)
setFaceavl(true);
clearTimeout(searchWaiting)
const avc = setTimeout(() => {
console.log()
setFaceavl(false);
setFace([])
}, 500)
setsearchWaiting(avc)
}}
onFaceDetectionError={(error) => {
console.log('face--detact-->', error)
}}
>
{({ camera, status, recordAudioPermissionStatus }) => {
if (status !== 'READY') return <PendingView />;
return (
<View style={{ flex: 0, flexDirection: 'row', justifyContent: 'center' }}>
<TouchableOpacity onPress={async () => {
const options = { quality: 0.5, base64: true };
const data = await camera.takePictureAsync(options)
if (faceavl) {
setTakeTimeFaceAvl(true)
} else {
setTakeTimeFaceAvl(false)
}
console.log(data.uri)
setImage(data)
setModalVisible(!modalVisible)
}} style={styles.capture}>
<Text style={{ fontSize: 14 }}> SNAP </Text>
</TouchableOpacity>
</View>
);
}}
</RNCamera>
{faces ? renderFaces() : null}
</SafeAreaView>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
{takeTimeFaceAvl ? image ? <Image
style={{
width: 200,
height: 100,
}}
source={{
uri: image.uri,
}}
/> : null : <Text>Face not found</Text>}
<TouchableOpacity
style={[styles.button, styles.buttonClose]}
onPress={() => setModalVisible(!modalVisible)}
>
<Text style={styles.textStyle}>Hide Modal</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
</>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'black',
},
item: {
backgroundColor: '#FFF',
},
viewOne: {
flexDirection: 'row'
},
viewTwo: {
alignItems: 'flex-end', marginEnd: 9
},
title: {
fontSize: 16, // Semibold #000000
color: '#000000',
},
noOff: {
color: '#D65D35',
fontSize: 20, // Semibold
}, product: {
color: '#A6A6A6',
fontSize: 16, // Regular
}, titleView: {
flex: 1,
alignSelf: 'center',
marginStart: 14,
marginEnd: 14,
},
centeredView: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 22
},
modalView: {
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 10,
alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5
},
button: {
borderRadius: 20,
padding: 10,
elevation: 2
},
buttonOpen: {
backgroundColor: "#F194FF",
},
buttonClose: {
backgroundColor: "#2196F3",
},
textStyle: {
color: "white",
fontWeight: "bold",
textAlign: "center"
},
modalText: {
marginBottom: 15,
textAlign: "center"
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
padding: 15,
paddingHorizontal: 20,
alignSelf: 'center',
margin: 20,
},
});

Resources