I have followed the guidelines of version 3.2.12,
and followed the instruction in the official document, but player id is not getting generated please help.
Initialization stopped after upgradation to 3.2.12, now they are not supporting initialization on componentWillMount()
import React, { Component } from "react";
import {
Text,
View,
Image,
TouchableOpacity,
I18nManager,
AsyncStorage,
Platform
} from "react-native";
import {
Container,
Right,
Item,
Input,
Header,
Left,
Body,
Title,
Form
} from "native-base";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import Ionicons from 'react-native-vector-icons/Ionicons';
// Screen Styles
import styles from "../Theme/Styles/Signin";
import Logo from "../image/qualpros.png";
import axios from 'axios';
import AwesomeAlert from 'react-native-awesome-alerts';
import OneSignal from 'react-native-onesignal';
class TutorSignInScreen extends Component {
static navigationOptions = {
header: null,
showAlert: false,
message: '',
}
state = {
data: [],
email: null,
password: null,
device_id: null,
showAlert : false
}
constructor(properties) {
super(properties);
OneSignal.init("my-onesignal-id");
OneSignal.addEventListener('received', this.onReceived);
OneSignal.addEventListener('opened', this.onOpened);
OneSignal.addEventListener('ids', this.onIds);
}
componentWillUnmount() {
OneSignal.removeEventListener("received", this.onReceived);
OneSignal.removeEventListener("opened", this.onOpened);
OneSignal.removeEventListener("ids", this.onIds);
}
onReceived(notification) {
console.log("Notification received: ", notification);
}
onOpened(openResult) {
console.log("Message: ", openResult.notification.payload.body);
console.log("Data: ", openResult.notification.payload.additionalData);
console.log("isActive: ", openResult.notification.isAppInFocus);
console.log("openResult: ", openResult);
}
onIds(device) {
let playerid = device.userId;
//console.log("Device info: ", playerid);
AsyncStorage.setItem('playerid', playerid);
this.setState ({
device_id: playerid
})
}
showAlert = () => {
this.setState({
showAlert: true
});
};
hideAlert = () => {
this.setState({
showAlert: false
});
};
signIn = async () => {
let device_type = (Platform.OS === 'ios') ? 'ios' : 'android'
try {
let { data } = await axios.post('url', {
email: this.state.email,
password: this.state.password,
//device_id: this.state.device_id,
device_id: '123test',
device_type: device_type
})
.then((response) => {
if (response.data.data.status === 'success') {
this.setState({ data: response.data.data })
console.log(response.data.data)
AsyncStorage.setItem('username', response.data.data.user_info.username);
AsyncStorage.setItem('userType', response.data.data.user_info.user_role_name);
AsyncStorage.setItem('latitude', response.data.data.user_info.latitude);
AsyncStorage.setItem('longitude', response.data.data.user_info.longitude);
AsyncStorage.setItem('user_id', response.data.data.user_info.user_id.toString());
AsyncStorage.setItem('user_role_id', response.data.data.user_info.user_role_id.toString());
this.props.navigation.navigate(response.data.data.user_info.user_role_name === 'Student' ? 'App' : 'Tutor')
} else {
this.setState({
message: response.data.data.message,
showAlert: true,
})
}
})
} catch (err) {
console.log(err);
}
}
showAlert = () => {
this.setState({
showAlert: true
});
};
hideAlert = () => {
this.setState({
showAlert: false
});
};
render() {
return (
<Container>
<Header style={styles.header}>
<Left style={styles.left}>
<TouchableOpacity
style={styles.backArrow}
onPress={() => this.props.navigation.navigate("Welcome")}
>
<View style={{ flexDirection: "row" }}>
<FontAwesome name="angle-left" size={30} color="black" />
<Text style={{ margin: 5, marginTop: 6, color: "black", fontSize: 12}}>Back</Text>
</View>
</TouchableOpacity>
</Left>
<Body style={styles.body} />
<Right style={styles.right} />
</Header>
<View style={styles.logosec}>
<Image source={Logo} style={styles.logostyle} />
</View>
<Form style={styles.form}>
<Item rounded style={styles.inputStyle}>
<Input
textAlign={I18nManager.isRTL ? "right" : "left"}
placeholder="Email"
style={styles.inputmain}
onChangeText={(email) => { this.setState({ email }) }}
autoCapitalize='none'
/>
</Item>
<Item rounded style={[styles.inputStyle, { marginTop: 10 }]}>
<Input
placeholder="Password"
secureTextEntry={true}
textAlign={I18nManager.isRTL ? "right" : "left"}
style={styles.inputmain}
onChangeText={(password) => { this.setState({ password }) }}
autoCapitalize='none'
/>
</Item>
<TouchableOpacity
info
style={styles.signInbtn}
onPress={this.signIn}
>
<Text autoCapitalize="words" style={styles.buttongetstarted}>
Sign In
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('ForgetPassword')}>
<Text autoCapitalize="words" style={styles.buttongettext}>
Forgot your password?
</Text>
</TouchableOpacity>
</Form>
<View style={styles.bottomView}>
{/* <TouchableOpacity
style={styles.fbButton}
onPress={() => alert("Facebook button Clicked")}
>
<View iconRight style={styles.fbview}>
<Ionicons name="logo-linkedin" size={30} color="white" />
<Text autoCapitalize="words" style={styles.fbButtonText}>
Sign in with LinkedIn
</Text>
</View>
</TouchableOpacity> */}
<TouchableOpacity
style={styles.bottomText}
onPress={() => { this.props.navigation.navigate('TutorSignUpScreen') }}>
<Text style={styles.bottomText01}>
Don't have an account?{" "}
<Text style={styles.bottomText02}>Sign up</Text>
</Text>
</TouchableOpacity>
</View>
<AwesomeAlert
show={this.state.showAlert}
showProgress={false}
//title="QualPros!"
message={this.state.message}
closeOnTouchOutside={true}
closeOnHardwareBackPress={false}
showConfirmButton={true}
confirmText="Ok"
confirmButtonColor="#d91009"
onConfirmPressed={() => {
this.hideAlert();
}}
/>
</Container>
);
}
}
export default TutorSignInScreen;
environment:
"react-native-onesignal": "^3.2.12",
"react": "16.6.1",
"react-native": "0.57.7"
Related
i need help guy, i get error on the closing tag
tried upload my type script and tried to enclose in a tag still showing errors.
this is a code i enlclose in a tag, i thought maybe it enclosed in class that it will work in function, i have really spent a lot of time on the
my react code. and i think the onpress gives error in the V tag too it highlights it i dont know what to do about that.
export default class Sqllogin extends Component {
constructor() {
super()
this.state = {
UserName: '',
UserEmail: '',
UserPassword: ''
}
}
Response = (props) => {
if(props.res == 'ok'){
return (
<Text style={styles.okText}>Login success</Text>
);
}else{
return (
<Text style={styles.errText}>Incorrect Login Details</Text>
);
}
}
[loaded] = useFonts({
SourceSansProLight,
SourceSansProRegular,
SourceSansProBold,
});
UserRegistrationFunction = () =>{
if(this.state.UserName !== ''){
Alert.alert(
this.state.UserName,
"My Alert Msg",
[
{ text: "OK", onPress: () => console.log("OK Pressed") }
]
);
}else{
return;
}
fetch('http://192.168.42.68/ENT/back_end/user', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: this.state.UserName,
email: this.state.UserEmail,
password: this.state.UserPassword
})
}).then((response) => response.text())
.then((responseJson) => {
// Showing response message coming from server after inserting records.
Alert.alert(
responseJson);
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
<View style={styles.container}>
<View style={{ flex: 1 }}>
<Image
style={{ flex: 1, width: null, marginTop: -500 }}
source={BackgroundImage}
/>
</View>
<Animatable.Text
style={styles.titleText}
animation='fadeInUp'
delay={1200}
>
Show Bookie
</Animatable.Text>
<View style={styles.bottomView}>
<Text style={styles.loginText}>Login</Text>
<Response res='Incorrect' />
<View style={styles.inputView}>
<Icon
style={styles.inputIcon}
name='person'
type='ionicons'
color='#5352ed'
/>
<TextInput
style={styles.input}
placeholder='Email'
onChangeText={email => this.setState({UserEmail : email})}
autoCapitalize='none'
keyboardType='email-address'
textContentType='emailAddress'
/>
</View>
<View style={styles.inputView}>
<Icon
style={styles.inputIcon}
name='lock'
type='ionicons'
color='#5352ed'
/>
<TextInput
style={styles.input}
placeholder='Password'
onChangeText={password => this.setState({UserPassword : password})}
secureTextEntry={true}
autoCapitalize='none'
/>
</View>
<Text style={styles.fpText}>Forgot Password?</Text>
<TouchableOpacity style={styles.loginButton} onPress={this.UserRegistrationFunction}>
<Text style={styles.loginButtonText}>Login</Text>
</TouchableOpacity>
<Text style={styles.registerText}>
Don't have an account?
<Text style={{ color: '#5352ed', fontFamily: 'SourceSansProBold' }}>
{' Register'}
</Text>
</Text>
</View>
</View>
</TouchableWithoutFeedback>//this is where error shows
);
}
}
thanks guys
This is probably a dumb question, but I've been following some react native / expo tutorials on how to make a login screen with Firebase. The tutorial I followed also made a loading screen (using a loading state) that will display while Firebase is connecting. Unfortunately, the loading state never ends for me, and I don't know how to fix it.
Here is my Navigator.js file:
import React, { useReducer } from "react";
import { View, ActivityIndicator } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from "#react-navigation/stack";
import { createDrawerNavigator } from "#react-navigation/drawer";
import { AuthContext } from '../contexts/UserContext';
import { firebase } from "../utils/FirebaseConfig";
import Login from "../screens/Login";
import Signup from "../screens/Signup";
import Home from "../screens/Home";
const Drawer = createDrawerNavigator();
const RootStack = createStackNavigator();
export default AppNavigation = (props) => {
const initialLoginState = {
isLoading: true,
user: null,
};
const loginReducer = (prevState, action) => {
switch (action.type) {
case 'LOGIN':
return {
...prevState,
user: action.user,
isLoading: false,
};
case 'LOGOUT':
return {
...prevState,
user: null,
isLoading: false,
};
case 'REGISTER':
return {
...prevState,
user: action.user,
isLoading: false,
};
}
};
const [loginState, dispatch] = useReducer(loginReducer, initialLoginState);
const authContext = React.useMemo(() => ({
signIn: async (email, password) => {
return firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(async (userCred) => {
dispatch({ type: 'LOGIN', user: userCred.user });
return true;
}).catch((error) => {
if (error.code === "auth/user-disabled") {
alert("User disabled!");
}
if (error.code === "auth/invalid-email") {
alert("That email address is invalid!");
}
if (error.code === "auth/user-not-found") {
alert("User not found, please sign up!");
}
if (error.code === "auth/wrong-password") {
alert("Wrong password!");
}
return false;
})
},
signOut: async () => {
return firebase.auth().signOut().then(async () => {
dispatch({ type: 'LOGOUT' });
});
},
signUp: (email, password) => {
return firebase.auth().createUserWithEmailAndPassword(email, password).then((userCred) => {
dispatch({ type: 'REGISTER', user: userCred.user });
}).catch((error) => {
if (error.code === "auth/email-already-in-use") {
alert("That email address is already in use!");
}
if (error.code === "auth/invalid-email") {
alert("That email address is invalid!");
}
if (error.code === "auth/operation-not-allowed") {
alert("Operation is not allowed!");
}
if (error.code === "auth/weak-password") {
alert("The password is too weak!");
}
return false;
})
}
}), []);
if (loginState.isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" color="grey" />
</View>
);
}
return (
<AuthContext.Provider value={authContext}>
<NavigationContainer>
{loginState.user !== null ? (
<Drawer.Navigator >
<Drawer.Screen name="Home" user={loginState.user} component={Home} />
</Drawer.Navigator>
) :
(
<RootStack.Navigator headerMode='none'>
<RootStack.Screen name="Login" component={Login} />
<RootStack.Screen name="Signup" component={Signup} />
</RootStack.Navigator>
)
}
</NavigationContainer>
</AuthContext.Provider>
)
}
Here is my Home.js File:
import React from 'react';
import { useContext } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { AuthContext } from "../contexts/UserContext";
function Home(props) {
const { signOut } = useContext(AuthContext);
return (
<View style={{ flex: 1 }}>
<Text>Welcome</Text>
<Text>Email: {props.user?.email}</Text>
<Text>uid: {props.user?.uid}</Text>
<Text>displayName: {props.user?.displayName}</Text>
<Text>photo: {props.user?.photoURL}</Text>
<TouchableOpacity onPress={() => signOut()} style={{ flexDirection: "row", alignItems: "center", justifyContent: "center", width: "100%" }} >
<Text style={{ fontWeight: "bold", fontSize: 18 }}>Logout</Text>
</TouchableOpacity>
</View>
);
}
export default Home;
Here is the Login.js file:
import React, { useContext, useState } from 'react';
import { KeyboardAvoidingView, View, Text, TextInput } from 'react-native';
import { AuthContext } from "../contexts/UserContext";
function Login(props) {
const [data, setData] = useState({
email: "",
password: ""
})
const { signIn } = useContext(AuthContext);
const emailInputChange = (val) => {
setData({
...data,
email: val
})
}
const passwordChange = (val) => {
setData({
...data,
password: val
});
}
const LoginHandle = () => {
signIn(data.email, data.password)
}
return (
<KeyboardAvoidingView>
<View style={{ flex: 1 }}>
<Text>Email: </Text>
<View >
<TextInput
placeholder="Email"
autoCapitalize="none"
onChangeText={(val) => emailInputChange(val)}
/>
</View>
<Text>Password: </Text>
<View>
<TextInput
placeholder="Password"
autoCapitalize="none"
secureTextEntry={true}
onChangeText={(val) => passwordChange(val)}
/>
</View>
<TouchableOpacity onPress={() => LoginHandle()} style={{ width: "100%", height: 50, justifyContent: "center", alignItems: "center", borderRadius: 10 }}>
<Text style={{ color: "#FFF", fontSize: 18, fontWeight: "bold" }}>Login</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
}
export default Login;
And finally, the Signup.js file:
import React, { useContext, useState } from 'react';
import { KeyboardAvoidingView, View, Text, TextInput } from 'react-native';
import { AuthContext } from "../contexts/UserContext";
function Signup(props) {
const [data, setData] = useState({
email: "",
password: ""
})
const { signUp } = useContext(AuthContext);
const emailInputChange = (val) => {
setData({
...data,
email: val
})
}
const passwordChange = (val) => {
setData({
...data,
password: val
});
}
const SignupHandle = () => {
signUp(data.email, data.password)
}
return (
<KeyboardAvoidingView>
<View style={{ flex: 1 }}>
<Text>Email: </Text>
<View >
<TextInput
placeholder="Email"
autoCapitalize="none"
onChangeText={(val) => emailInputChange(val)}
/>
</View>
<Text>Password: </Text>
<View>
<TextInput
placeholder="Password"
autoCapitalize="none"
secureTextEntry={true}
onChangeText={(val) => passwordChange(val)}
/>
</View>
<TouchableOpacity onPress={() => SignupHandle()} style={{ width: "100%", height: 50, justifyContent: "center", alignItems: "center", borderRadius: 10 }}>
<Text style={{ color: "#FFF", fontSize: 18, fontWeight: "bold" }}>Signup</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
}
export default Signup;
I have a problem.
I want after I successfully add product to cart my shopping cart badge will be updated. But I can't setState the itemCart component.
This is code when i add products in cart.
Function _datmon() will do that.
import React, { Component } from 'react';
import {View,Text,StyleSheet,Dimensions,Image, TouchableOpacity,Modal, Button, Alert} from 'react-native';
import { RecyclerListView, DataProvider, LayoutProvider } from "recyclerlistview";
import { Snackbar} from 'react-native-paper';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import AsyncStorage from '#react-native-community/async-storage';
import Home from '../Home';
import 'regenerator-runtime/runtime';
export default class FoodByList extends Component{
constructor(props){
super(props);
this.state={
mang:[],
dataProvider: new DataProvider ((r1,r2)=> r1!==r2),
statusInform:false,
modalVisible: false,
id:'',
gia:'',
mota:'',
soluong:1,
mangmonan:[{
id:'',
soluong:'',
}],
getArr:[],
hide: true,
}
this.home = new Home();
this.homeref = React.createRef();
}
openModalWithItem(item) {
this.setState({
ten: item.ten,
gia: item.gia,
hinhanh: item.hinhanh,
id: item.id,
mota: item.mota,
})
}
layoutProvider = new LayoutProvider(
index => {
return index;
},
(type,dim) => {
dim.width = Dimensions.get('window').width/2;
dim.height = 280;
}
)
_datmon = async()=>{
//Get array availible device
try {
const myArray = await AsyncStorage.getItem('keyOrdermonan');
if (myArray !== null) {
// We have data!!
console.log(JSON.parse(myArray));
}
} catch (error) {
// Error retrieving data
console.log(error);
}
const myArray = await AsyncStorage.getItem('keyOrdermonan');
if(myArray !=null){
this.state.getArr = JSON.parse(myArray);
//Id food currently
const check = {id:this.state.id};
var position = 0;
//Check id avalilabled in cart ?
const police = this.state.getArr.some(getA => getA.id===check.id );
if(police==true){
for(var i =0;i<this.state.getArr.length;i++){
if(this.state.getArr[i].id==this.state.id){
break;
}else{
position+=1;
}
}
this.state.getArr[position].soluong += this.state.soluong;
this.setState({mangmonan: this.state.getArr});
this.homeref.setSizeCart(this.state.mangmonan.length);
console.log('Completely udrage quanity');
}
else if(police==false){
this.setState({mangmonan: [{id: this.state.id,
soluong: this.state.soluong,
}].concat(this.state.getArr)});
this.homeref.setSizeCart(this.state.mangmonan.length);
}
}else{
this.setState({mangmonan: [{id: this.state.id,
soluong: this.state.soluong,
}]});
this.homeref.setSizeCart(this.state.mangmonan.length);
}
// Add new cart
try {
await AsyncStorage.setItem('keyOrdermonan', JSON.stringify(this.state.mangmonan));
// await AsyncStorage.removeItem('keyOrdermonan');
this.setState({modalVisible:false,soluong:1});
Alert.alert(
"Thành công",
"Đặt món thành công, vui lòng kiểm tra giỏ hàng",
[
{
text: "Kiểm tra giỏ hàng",
onPress: ()=>{this.props.navigation.navigate('cart')}
},
{
text: "Tiếp tục đặt món",
style:'cancel'
},
]
);
} catch (error) {
// Error saving data
console.log(error);
}
}
getPriceVND = (giatri) => {
const parts = giatri.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const gia = parts.join(".");
return gia;
}
rowrender = (type,item) => {
return(
<View style={styles.bgitem}>
<TouchableOpacity style={styles.wrapperitem} onPress={()=> {this.setState({modalVisible:true}),this.openModalWithItem(item)}}>
<View style={styles.wrapperimg}>
<Image source={{ uri: item.hinhanh }} style={styles.img}/>
</View>
</TouchableOpacity>
<View style={styles.wrappername}>
<Text style={{ fontWeight:'bold' }}>Tên món ăn:</Text>
<Text style={styles.under}>{item.ten}</Text>
</View>
<View style={styles.wrappername}>
<Text style={{ fontWeight:'bold' }}>Giá: </Text>
<Text style={styles.under}>{this.getPriceVND(item.gia)}đ</Text>
</View>
</View>
)
}
componentDidMount(){
//set lại tittle bar
this.props.navigation.setOptions({title:this.props.route.params.tendanhmuc});
fetch("http://192.168.43.25/DemoJWT/getMonAnByList.php",{
method:'POST',
headers: {
"Accept":"application/json",
"Content-Type":"application/json"
},
body: JSON.stringify({
"IDDANHMUC" : this.props.route.params.id,
})
})
.then((reponse)=>reponse.json())
.then((reponseJson)=>{
if(reponseJson==""){
this.setState({statusInform:true});
}else{
this.setState({
mang:reponseJson,
dataProvider:this.state.dataProvider.cloneWithRows(reponseJson),
})
}
})
.catch((err)=>{
console.log(err);
})
}
render(){
return(
<View style={styles.wrapper}>
{!this.state.hide && <Home ref={this.homeref} />}
{ !this.state.dataProvider.getSize()==0 &&
<RecyclerListView
layoutProvider={this.layoutProvider}
rowRenderer={this.rowrender}
dataProvider = {this.state.dataProvider}
/>
}
{/* Thông báo khi không có món */}
<Snackbar
visible={this.state.statusInform}
onDismiss={()=>{this}}
action={{
label: 'Trở về',
onPress: () => {
this.props.navigation.goBack()
},
}}>
Hiện nhà hàng chưa có các món ăn này.
Mong quý khách thông cảm !
</Snackbar>
{/* Thông báo khi không có món */}
{/* Hiển thị khi nhấn chi tiết món ăn để đặt hàng */}
<View>
<Modal
animationType="slide"
transparent={true}
visible={this.state.modalVisible}
>
<View style={styles.modalView}>
<View style={styles.wrapperimgModal}>
<Image source={{ uri: this.state.hinhanh }} style={styles.imgModal}/>
<View style={styles.wrappername,{marginTop:15}}>
<Text style={{ fontWeight:'bold',fontSize:18, }}>Tên món ăn:</Text>
<Text >{this.state.ten}</Text>
</View>
<View style={{ flexDirection:'column' }}>
<Text style={{ fontWeight:'bold',fontSize:18, }}>Giá: </Text>
<Text>{this.getPriceVND(this.state.gia)} đ / 1 phần</Text>
</View>
<View style={styles.wrappername}>
<Text style={{ fontWeight:'bold',fontSize:18, }}>Mô tả:</Text>
<Text>{this.state.mota}</Text>
</View>
<View style={styles.wrappername}>
<Text style={{ fontWeight:'bold',fontSize:18, }}>Số lượng:</Text>
<View style={{ flexDirection:'row',marginLeft:0,marginTop:10 }}>
<TouchableOpacity style={styles.decrease} onPress={()=>{
if(this.state.soluong==1){
console.log('Không giảm nữa');
}else{
this.setState({soluong:this.state.soluong-1})
}
}}>
<MaterialCommunityIcons name='minus-circle' color="black" size={24} />
</TouchableOpacity>
<Text>{this.state.soluong}</Text>
<TouchableOpacity style={styles.increase} onPress={()=>{
if(this.state.soluong==15){
console.log('Không tăng nữa');
}
else{
this.setState({soluong:this.state.soluong+1})
}
}}>
<MaterialCommunityIcons name='plus-circle' color="black" size={24} />
</TouchableOpacity>
</View>
</View>
</View>
<View style={styles.totalbtn}>
<View style={styles.btn}>
<Button
title="Hủy"
onPress={()=>{this.setState({modalVisible:false,soluong:1})}}
/>
</View>
<View style={styles.btn2}>
<Button title="Đặt ngay"
onPress={()=>{this._datmon()}}
/>
</View>
</View>
</View>
</Modal>
</View>
{/* Hiển thị khi nhấn chi tiết món ăn để đặt hàng */}
</View>
)
}
}
const styles = StyleSheet.create({
wrapper:{
flex:1,
},
wrapperitem:{
flex:1,
},
title:{
fontSize:30,
padding:10,
fontWeight:'bold',
},
bgitem:{
flex:1,
flexDirection:'column',
padding:10,
margin:10,
borderWidth:1,
borderRadius:15,
backgroundColor:'#dddddd',
},
wrapperimg:{
width:"100%",
height:180,
alignItems:'center',
padding:5,
},
wrapperimgModal:{
width:"100%",
height:370,
padding:5,
marginLeft:10,
},
img:{
width:'80%',
height:100,
borderRadius:10,
},
imgModal:{
width:'100%',
height:150,
borderRadius:10,
},
wrappername:{
flexDirection:'column',
},
under:{
paddingLeft:10,
},
modalView: {
margin: 20,
marginTop:100,
backgroundColor: "white",
borderRadius: 20,
padding: 35,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5
},
totalbtn:{
flexDirection:'row',
alignItems:'center',
justifyContent:'center'
},
btn:{
width:90,
marginRight:10,
},
btn2:{
width:90,
marginLeft:10,
},
decrease:{
marginRight:10,
},
increase:{
marginLeft:10
}
})
Still here is your code setSizeCart() in class component Home.js :
import React, { Component } from "react";
import {StyleSheet, Alert,View, StatusBar,Linking, Text} from "react-native"
import AsyncStorage from '#react-native-community/async-storage';
import HomeScreen from "./Screen/HomeScreen";
import FavouriteScreen from "./Screen/FavouriteScreen";
import ProfileScreen from "./Screen/ProfileScreen";
import CartScreen from "./Screen/CartScreen";
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import { Appbar, Snackbar,Badge } from 'react-native-paper';
import NetInfo from "#react-native-community/netinfo";
import {createDrawerNavigator} from "#react-navigation/drawer"
import { DrawerActions } from '#react-navigation/native';
import SettingScreen from "./Screen/SettingScreen";
import BookingScreen from "./Screen/BookingScreen";
import FullFood from "./Screen/FullFood";
import 'regenerator-runtime/runtime';
const Drawer = createDrawerNavigator();
export default class Home extends Component{
_isMounted = false;
constructor(props){
super(props);
this.state={
token:"",
ten:"",
statusInform:false,
searchQuery:"",
getMangAsync:[],
itemcart: 0 ,
}
this.setSizeCart = this.setSizeCart.bind(this);
}
setSizeCart (bien){
try {
this.setState({ itemcart: bien });
console.log("set thành công");
} catch (error) {
console.log(error);
}
}
_getasyc = async()=>{
try {
const key = await AsyncStorage.getItem("keyOrdermonan");
if(key!==null){
this.setState({getMangAsync:JSON.parse(key)});
this.setState({itemcart:this.state.getMangAsync.length});
}
} catch (error) {
console.log(error)
}
}
checkInternet(){
NetInfo.fetch("http://192.168.43.25/DemoJWT/checkToken.php")
.then(state=>{
console.log(state.isConnected)
if(state.isConnected==false){
this.setState({statusInform:true})
}
})
}
componentDidMount(){
this._isMounted = true;
if(this._isMounted){
this.checkInternet();
this._getasyc();
}
}
componentWillUnmount(){
this._getasyc();
// console.log("đã"+ this._isMounted)
}
_logout = async() =>{
try {
await AsyncStorage.removeItem("keyToken");
Alert.alert("Đăng xuất");
this.props.navigation.navigate('login');
} catch (error) {
console.log(error)
}
}
contact(){
Alert.alert(
"Liên hệ với chúng tôi",
"Bạn có muốn hay không?",
[
{
text: "Hủy",
style:'cancel'
},
{
text: "Đồng ý",
onPress: ()=>Linking.openURL('tel:$+84705982473')
}
]
)
}
render(){
// const {ten} = this.props.route.params
return(
<View style={{ flex:1 }}>
<StatusBar backgroundColor='#555555' barStyle="light-content" />
<Appbar style={styles.appbar}>
<Appbar.Action icon="format-list-bulleted" onPress={()=>(this.props.navigation.dispatch(DrawerActions.openDrawer()))}/>
<Appbar.Content title="GREAT FOOD" />
<Badge
visible={this.state.itemcart && this.state.itemcart >0}
size={17}
style={{ position: 'absolute', top: 5, right: 55 }}>{this.state.itemcart}</Badge>
<Appbar.Action icon="cart" onPress={()=>{this.props.navigation.navigate('cart')}}/>
<Appbar.Action icon="phone-in-talk" onPress={()=>{this.contact()}}/>
</Appbar>
<Drawer.Navigator
overlayColor="transparent"
>
<Drawer.Screen name ="home" component={HomeScreen}
options={{
drawerLabel:"Menu",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="home" color={color} size={26} />
), }}
/>
<Drawer.Screen name="profile" component={ProfileScreen}
options={{
drawerLabel:"Hồ sơ",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="account-circle" color={color} size={26} />
), }}
/>
<Drawer.Screen name="fullfood" component={FullFood}
options={{
drawerLabel:"Tất cả món ăn",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="food" color={color} size={26} />
), }}
/>
<Drawer.Screen name= "favourite" component={FavouriteScreen}
options={{
drawerLabel:"Yêu thích",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="heart-pulse" color={color} size={26} />
), }}
/>
<Drawer.Screen name= "booking" component={BookingScreen}
options={{
drawerLabel:"Đặt bàn",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="table-furniture" color={color} size={26} />
), }}
/>
<Drawer.Screen name="cart" component={CartScreen}
options={{
drawerLabel:"Giỏ hàng",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="cart" color={color} size={26} />
), }}
/>
<Drawer.Screen name="setting" component={SettingScreen}
options={{
drawerLabel:"Cài đặt",
drawerIcon:({color})=>(
<MaterialCommunityIcons name="wrench-outline" color={color} size={26} />
), }}
/>
</Drawer.Navigator>
<Snackbar
visible={this.state.statusInform}
onDismiss={()=>{this}}
action={{
label: 'Tắt',
onPress: () => {
this.setState({statusInform:false})
},
}}>
Vui lòng kiểm tra kết nối.
</Snackbar>
</View>
)
}
}
const styles = StyleSheet.create({
wrapper:{
flex:1,
justifyContent:"center",
alignItems:'center',
},
logout:{
marginTop:50,
},
appbar:{
backgroundColor:'#555555'
},
})
And I have been received warning is:
Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the Home component.
Can anyone help me!
So one small thing you are missing here is that,
Creating a new component using the new keyword is not going to mount that component into the render tree.
You should include it inside the render function of your FoodByList like this
<Home ref={this.homeRef} />
Then, in the constructor of your FoodByList component, create the homeRef using
this.homeRef = React.createRef();
More on React.createRef in this article.
Basically assigning a ref to the Home component inside the render of FoodByList gives you the ability to call the functions inside the Home component.
Next, in Home component's constructor use this.setSizeCart = this. setSizeCart.bind(this) or else convert the setSizeCart function into an arrow function like this
setSizeCart = (bien) => {
try {
this.setState({ itemcart: bien });
console.log("set successfully");
} catch (error) {
console.log(error);
}
}
So now, instead of doing
this.home.setSizeCart(this.state.mangmonan.length)
you should be doing
this.homeRef.current.setSizeCart(this.state.mangmonan.length)
I am pretty new to React Native, so if the question seems stupid i am sorry in advance, i have been trying for hours to get this to work before asking this question.
I am trying to pass data from a text input to the next screen using firebase database.
I keep getting the error JSON Parse error: Unexpected identifier "undefined", I have attached below my two files, one with the text input (InputForm.js) and the other one which i want to show that data on the screen (ASTConfig1screen)
If anyone can help with this you really are a superstar!
InputForm.js
import React, { Component } from 'react';
import { StyleSheet, ScrollView, ActivityIndicator, View, TextInput } from 'react-native';
import { Button } from 'react-native-elements';
import firebase from '../Firebase';
import { withNavigation } from 'react-navigation';
class InputForm extends Component {
constructor() {
super();
this.ref = firebase.firestore().collection('boards');
this.state = {
name: '',
inventoryclass: '',
outlet: '',
isLoading: false,
};
}
updateTextInput = (text, field) => {
const state = this.state
state[field] = text;
this.setState(state);
}
saveBoard() {
this.setState({
isLoading: true,
});
this.ref.add({
name: this.state.name,
inventoryclass: this.state.inventoryclass,
outlet: this.state.outlet,
}).then((docRef) => {
this.setState({
name: '',
outlet: '',
inventoryclass: '',
isLoading: false,
});
this.props.navigation.navigate('ASTConfig1');
})
.catch((error) => {
console.error("Error adding document: ", error);
this.setState({
isLoading: false,
});
});
}
render() {
if(this.state.isLoading){
return(
<View style={styles.activity}>
<ActivityIndicator size="large" color="#ffa500"/>
</View>
)
}
return (
<ScrollView style={styles.container}>
<View style={styles.subContainer}>
<TextInput style={styles.inputtext}
placeholder={'Name'}
placeholderTextColor="white"
value={this.state.name}
onChangeText={(text) => this.updateTextInput(text, 'name')}
/>
</View>
<View style={styles.subContainer}>
<TextInput style={styles.inputtext}
multiline={true}
numberOfLines={4}
placeholder={'Inventory Class'}
placeholderTextColor="white"
value={this.state.inventoryclass}
onChangeText={(text) => this.updateTextInput(text, 'inventoryclass')}
/>
</View>
<View style={styles.subContainer}>
<TextInput style={styles.inputtext}
placeholder={'Outlet'}
placeholderTextColor="white"
value={this.state.outlet}
onChangeText={(text) => this.updateTextInput(text, 'outlet')}
/>
</View>
<View style={styles.button}>
<Button
large
leftIcon={{name: 'save'}}
title='Save'
onPress={() => this.saveBoard()} />
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20
},
subContainer: {
flex: 1,
marginBottom: 20,
padding: 5,
borderBottomWidth: 2,
borderBottomColor: '#CCCCCC',
},
inputtext: {
color: 'white',
fontSize: 20
},
activity: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
}
})
export default withNavigation(InputForm);
and this is where i would like to show the data on this screen
ASTConfig1.js
import React from 'react';
import {
View,
Text,
StyleSheet,
Button,
ImageBackground,
StatusBar,
SafeAreaView,
TextInput,
ScrollView,
UIManager,
ActivityIndicator
}
from 'react-native';
import {AccordionList} from "accordion-collapse-react-native";
import { Separator } from 'native-base';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
import firebase from '../Firebase';
import Logo from '.././components/Logo';
import Colors from '.././constants/Colors';
import Search from '.././components/Search';
import InputForm from '.././components/InputForm';
class ASTConfig1Screen extends React.Component {
static navigationOptions = {
title: 'ASTConfig1',
};
constructor(props) {
super(props);
this.state= {
isLoading: true,
board: {},
key: '',
status:true,
text: '',
list:[
{
title: 'Getting Started',
body: 'React native Accordion/Collapse component, very good to use in toggles & show/hide content'
},
{
title: 'Components',
body: 'AccordionList,Collapse,CollapseHeader & CollapseBody'
},
{
title: 'Test',
body: 'AccordionList,Collapse,CollapseHeader & CollapseBody'
}
],
}
}
componentDidMount() {
const { navigation } = this.props;
const ref = firebase.firestore().collection('boards').doc(JSON.parse(navigation.getParam('boardkey')));
ref.get().then((doc) => {
if (doc.exists) {
this.setState({
board: doc.data(),
key: doc.id,
isLoading: false
});
} else {
console.log("No such document!");
}
});
}
_head(item){
return(
<Separator bordered style={{alignItems:'center'}}>
<Text>{item.title}</Text>
</Separator>
);
}
_body(item){
return (
<View style={{padding:10}}>
<Text style={{textAlign:'center'}}>{item.body}</Text>
</View>
);
}
ShowHideTextComponentView = () =>{
if(this.state.status == true)
{
this.setState({status: false})
}
else
{
this.setState({status: true})
}
}
render() {
if(this.state.isLoading){
return(
<View style={styles.activity}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
)
}
return (
<View style={styles.screen}>
<ImageBackground
source={require('.././assets/Img/BackGround2.png')}
style={styles.background}>
</ImageBackground>
<SafeAreaView>
<View style={{flex: 1, justifyContent: 'space-between', width: wp('80%')}}>
<View style={styles.logotop}>
<Logo/>
</View>
<View style={styles.editstock}>
<Text style={styles.editstocktext}>EDIT STOCK LIST:</Text>
</View>
{/*Start of 3 buttons Firebase*/}
<View style={styles.three}>
<View style={styles.edit1}>
<Text style={styles.textheader}>{this.state.board.name}</Text>
<Button style={styles.edit} title='Edit' ></Button>
</View>
<View style={{padding: 3}}></View>
<View style={styles.edit2}>
<Text style={styles.text}>{this.state.board.inventoryclass}</Text>
<Button style={styles.edit} title='Edit' ></Button>
</View>
<View style={styles.edit3}>
<Text style={styles.text}>{this.state.board.outlet}</Text>
<Button style={styles.edit} title='Edit' ></Button>
</View>
</View>
{/*End of 3 buttons Firebase*/}
{/*Start of AccordionList*/}
<ScrollView>
<View style={styles.middle}>
<AccordionList
list={this.state.list}
header={this._head}
body={this._body}
/>
</View>
</ScrollView>
{/*End of AccordionList*/}
{/*Start of Search*/}
<View>
{
this.state.status ? null : <View style={styles.bottom}>
<Text style={styles.textbottom}>SEARCH FOR NEW ITEMS:</Text>
<Search />
</View>
}
<Button title="ADD" onPress={this.ShowHideTextComponentView} />
</View>
</View>
</SafeAreaView>
</View>
);
};
};
{/*End of Search*/}
export default ASTConfig1Screen;
but it returns the error - Error adding document: [SyntaxError: SyntaxError: SyntaxError: JSON Parse error: Unexpected identifier "undefined"
in inputform.js saveBoard function you should
this.props.navigation.navigate('Details', {
'ASTConfig1': docRef
});
and remove JSON.parse form other file
I'm using https://facebook.github.io/react-native/docs/navigation.html by the way.
I'm trying to use the StackNavigator to go from Login.js to AboutDendro.js. What's wrong in my <Button/> component that's throwing that error in my iOS simulator?
Here's Login.js:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ScrollView, Text, TextInput, View, Button, StyleSheet } from 'react-native';
import { login } from '../redux/actions/auth';
import {AuthenticationDetails, CognitoUser, CognitoUserAttribute, CognitoUserPool} from '../lib/aws-cognito-identity';
import StackNavigator from 'react-navigation';
import AboutDendro from './AboutDendro';
const awsCognitoSettings = {
UserPoolId: 'something',
ClientId: 'something'
};
class Login extends Component {
constructor (props) {
super(props);
this.state = {
page: 'Login',
username: '',
password: ''
};
}
get alt () { return (this.state.page === 'Login') ? 'SignUp' : 'Login'; }
handleClick (e) {
e.preventDefault();
const userPool = new CognitoUserPool(awsCognitoSettings);
// Sign up
if (this.state.page === 'SignUp') {
const attributeList = [
new CognitoUserAttribute({ Name: 'email', Value: this.state.username })
];
userPool.signUp(
this.state.username,
this.state.password,
attributeList,
null,
(err, result) => {
if (err) {
alert(err);
this.setState({ username: '', password: '' });
return;
}
console.log(`result = ${JSON.stringify(result)}`);
this.props.onLogin(this.state.username, this.state.password);
}
);
} else {
const authDetails = new AuthenticationDetails({
Username: this.state.username,
Password: this.state.password
});
const cognitoUser = new CognitoUser({
Username: this.state.username,
Pool: userPool
});
cognitoUser.authenticateUser(authDetails, {
onSuccess: (result) => {
console.log(`access token = ${result.getAccessToken().getJwtToken()}`);
this.props.onLogin(this.state.username, this.state.password);
},
onFailure: (err) => {
alert(err);
this.setState({ username: '', password: '' });
return;
}
});
}
}
togglePage (e) {
this.setState({ page: this.alt });
e.preventDefault();
}
static navigationOptions = {
title: 'AboutDendro',
};
render() {
const { navigate } = this.props.navigation;
const App = StackNavigator({
Home: { screen: Login },
Profile: { screen: AboutDendro },
});
return (
<ScrollView style={{padding: 20}}>
<Button
title="Go to Jane's profile"
onPress={() =>
navigate('AboutDendro', { name: 'AboutDendro' })
}
/>
<Text style={{fontSize: 27}}>{this.state.page}</Text>
<TextInput
placeholder='Email Address'
autoCapitalize='none'
autoCorrect={false}
autoFocus={true}
keyboardType='email-address'
value={this.state.username}
onChangeText={(text) => this.setState({ username: text })} />
<TextInput
placeholder='Password'
autoCapitalize='none'
autoCorrect={false}
secureTextEntry={true}
value={this.state.password}
onChangeText={(text) => this.setState({ password: text })} />
<View style={{margin: 7}}/>
<Button onPress={(e) => this.handleClick(e)} title={this.state.page}/>
<View style={styles.firstView}>
<Text onPress={(e) => this.togglePage(e)} style={styles.buttons}>
{this.alt}
</Text>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
buttons: {
fontSize: 12,
color: 'blue',
flex: 1
},
firstView: {
margin: 7,
flexDirection: 'row',
justifyContent: 'center'
}
});
const mapStateToProps = (state, ownProps) => {
return {
isLoggedIn: state.auth.isLoggedIn
};
}
const mapDispatchToProps = (dispatch) => {
return {
onLogin: (username, password) => { dispatch(login(username, password)); }
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
It is because navigation is not in your props. It is a part of your App component you created. But you do nothing with this component.
You should have an App.js file, with your stackNavigator, set your Login component as your default component in your stackNavigator's parameters.
Take a look at this documentation
I try to refactor your code.
in component render maybe you can just write :
render() {
const { navigate } = this.props.navigation;
return (
<ScrollView style={{padding: 20}}>
<Button
title="Go to Jane's profile"
onPress={() =>
navigate('Profile', { name: 'AboutDendro' })
}
/>
<Text style={{fontSize: 27}}>{this.state.page}</Text>
<TextInput
placeholder='Email Address'
autoCapitalize='none'
autoCorrect={false}
autoFocus={true}
keyboardType='email-address'
value={this.state.username}
onChangeText={(text) => this.setState({ username: text })} />
<TextInput
placeholder='Password'
autoCapitalize='none'
autoCorrect={false}
secureTextEntry={true}
value={this.state.password}
onChangeText={(text) => this.setState({ password: text })} />
<View style={{margin: 7}}/>
<Button onPress={(e) => this.handleClick(e)} title={this.state.page}/>
<View style={styles.firstView}>
<Text onPress={(e) => this.togglePage(e)} style={styles.buttons}>
{this.alt}
</Text>
</View>
</ScrollView>
);
}
}
And you separate component StackNavigation below component render() like:
const App = StackNavigator({
Home: { screen: Login },
Profile: { screen: AboutDendro },
});
And then import component App in your index.ios.js like:
import './Login';
just that. Maybe my answer can help you.