React native authentication using laravel backend API - javascript

I'm new to react-native. I currently try to set the login of react-native by using the Laravel API. The API that I used already tested and its work. But when I tried to put in the react-native, it shows the error while i called the API.
The warning in the emulator is:
Possible Unhandled Promise Rejection (id:0):
TypeError: Network request failed
Here is my code.
import React, { Component } from 'react';
import {
StyleSheet,
View,
TextInput,
Text,
TouchableOpacity,
Alert,
AsyncStorage,
} from 'react-native';
import {Actions} from 'react-native-router-flux';
import Logo from '../components/Logo';
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
}
};
signup(){
Actions.signup()
}
home(){
Actions.home()
}
handleLogin = () => {
fetch('http://localhost:8888/api/login',{
method: 'POST',
header:{
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
})
})
.then((response) => response.json())
.then((res) => {
if (res.success === true){
alert(res.message)
}else{
alert(res.message)
}
alert('test')
})
}
render() {
return (
<View style={styles.container}>
<Logo/>
<View style={styles.inputContainer}>
<TextInput style={styles.inputBox}
underlineColorAndroid='0,0,0,0'
placeholder='Email'
placeholderTextColor= 'grey'
keyboardType= 'email-address'
onChangeText={(text) => this.setState({email:text})}
onSubmitEditing={()=> this.password.focus()}
/>
<TextInput style={styles.inputBox}
underlineColorAndroid='0,0,0,0'
placeholder='Password'
placeholderTextColor= 'grey'
secureTextEntry= {true}
ref={(input) => this.password = input}
onChangeText={(text) => this.setState({password:text})}
/>
<TouchableOpacity style={styles.button} onPress={this.handleLogin}>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
</View>
<View style={styles.signupText}>
<Text>Don't have an account? </Text>
<TouchableOpacity onPress={this.signup}>
<Text style={styles.signupButton}>Signup</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
Anyone know what's the problem?

Problem solved by setup the adb and use the adb reverse command.
EXAMPLE
adb reverse tcp:8081 tcp:3333
https://stackoverflow.com/a/39108921/12988525

Related

React native code is unable to send data to django api

I am a beginner and I'm using Django in the backend of my react native app. I am unable to add data to the django admin panel from my app using fetch method. I am not getting any errors but my data is not getting posted to the backend.I have used the django api as the url in fetch method.
Please let me know if any other code snippet is required to check.
Would appreciate some help here.
export class LoginScreen extends Component {
constructor() {
super();
this.state = {
email: '',
name: '',
};
}
updateValue(text, field) {
if (field == 'email') {
this.setState({
email: text,
});
} else if (field == 'pwd') {
this.setState({
pwd: text,
});
}
}
submit() {
let collection = {};
collection.email = this.state.email;
collection.pwd = this.state.pwd;
console.warn(collection);
let url='http://10.0.0.2:8000/api/mdlApp/'
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(collection),
})
.then((response) => response.json())
.then((collection) => {
console.log('Success:', collection);
})
.catch((error) => {
console.error('Error:', error);
});
}
render() {
return (
<ImageBackground source={require('../images/bg4.png')} style={styles.bg}>
<SafeAreaView style={styles.container}>
<Logo />
<View style={styles.container1}>
<TextInput
style={styles.inputBox}
name="email"
placeholder="Enter Your Email"
placeholderTextColor="#ffffff"
onChangeText={(text) => this.updateValue(text, 'email')}
/>
<TextInput
style={styles.inputBox}
name="pwd"
placeholder="Enter Your Password"
secureTextEntry={true}
placeholderTextColor="#ffffff"
onChangeText={(text) => this.updateValue(text, 'pwd')}
/>
<TouchableOpacity
//onPress={() => this.props.navigation.navigate('HomeApp')}
onPress={() => this.submit()}
style={styles.button}
htmlType="submit">
<Text style={styles.buttonText}> LOGIN </Text>
</TouchableOpacity>
</View>
<View style={styles.signupTextCont}>
<Text style={styles.signupText}>Don't have an account yet?</Text>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Register')}
style={styles.signupButton}>
<Text>Register Now</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
</ImageBackground>
);
}
}
change ur code as follows..install axios first
submit = () => {
const url='http://10.0.0.2:8000/api/mdlApp/'
let collection = {
email: this.state.email,
pwd: this.state.pwd
};
axios.post(`${url}`, collection, {
headers: {
'content-type': 'application/json'
}
} ).then(res => {
console.log(res.data)
}))
}

Error when navigating to a page after creating stackNavigator in react-native

I am creating an app with react-native and I would like to use createStackNavigator to have three screens. I have a button that I would like to be used to take the user to the third screen.
Here is my code for createStackNavigator
const RootStack = createStackNavigator({
Login: {
screen: LoginActivity
},
Profile: {
screen: ProfileActivity
},
MakeAccount: {
screen: MainProject
}
});
const AppContainer = createAppContainer(RootStack);
export default AppContainer;
Here is my code for the button that navigate to the page/screen
<Button title="Click Here To Create an Account" onPress={() => this.props.navigation.navigate('MakeAccount')} color="#2196F3" />
When I run my app on an iso simulator with Xcode, I get the following message:
I don't know why this is happening...
Also, here's my MainProject class:
class MainProject extends Component {
constructor(props) {
super(props)
this.state = {
UserName: '',
UserEmail: '',
UserPassword: ''
}
}
UserRegistrationFunction = () => {
const { UserName } = this.state;
const { UserEmail } = this.state;
const { UserPassword } = this.state;
fetch('http://ip/user_registration.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: UserEmail,
password: UserPassword
})
}).then((response) => response.json())
.then((responseJson) => {
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<View style={styles.MainContainer}>
<Text style={{ fontSize: 20, color: "#000", textAlign: 'center', marginBottom: 15}}>User Registron Form</Text>
<TextInput
placeholder="Enter User Name"
onChangeText={UserName => this.setState({UserName})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Email"
onChangeText={UserEmail => this.setState({UserEmail})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Password"
onChangeText={UserPassword => this.setState({UserPassword})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
secureTextEntry={true}
/>
<Button title="Click Here To Register" onPress={this.UserRegistrationFunction} color="#2196F3" />
</View>
);
}
}
export default MainProject;
Looking at the code you have posted here, it seems that the creation of stackNavigator is ok. The error message is very clear about the problem:
"MakeAccount" must be a React Component.
So, it probably means that you are not extending React.Component on MainProject class, or your imports/exports are not correct either where the MainProject are being instantiated OR where you are importing the class (That should be in the same file that you create the stack).
It needs to be something like this, on the file where you instantiate MainProject:
import React from "react";
export default class MainProject extends React.Component {
...
}
Then import it where you are creating the navigator as:
import MainProject from "./CompletePathToMainProject";
...
//Your logic of stackNavigator creation
I don't know how your folders and files are structured, so above CompletePathToMainProject means something like ./account/MainProject.js based on the informations you gave until now

React Native error when passing size of ActivityIndicator as a prop

I was creating a reusable spinner component for my project I had created 2 components: loginform and spinner, where i passed an enum as a prop from loginform to spinner when I reloaded the app it crashed on android but thankfully it displayed an error message on iOS saying "Error while updating property 'width' in shadow node of type: AndroidProgressBar".
I've tried removing the reference to the prop and instead specified the enum values i.e., 'small' or 'large' to the spinner component. It worked but that completely destroyed the whole point of creating a reusable component.
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import firebase from 'firebase';
import { Button, Card, CardSection, Input, Spinner } from './common/';
class LoginForm extends Component {
state = { email: '', password: '', error: '', loading: false };
onButtonPress() {
const { email, password } = this.state;
this.setState({ error: '', loading: true });
firebase.auth().signInWithEmailAndPassword(email, password)
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.catch(() => {
this.setState({ error: 'Authentication Failed!' });
});
});
}
renderButton() {
if (this.state.loading) {
return <Spinner size="small" />;
}
return <Button onPress={this.onButtonPress.bind(this)}>Log In</Button>;
}
render() {
return (
<View style={{ marginTop: 50 }}>
<Card>
<CardSection>
<Input
autoCorrect={false}
label='Email :'
placeholder='user#example.com'
value={this.state.email}
onChangeText={email => this.setState({ email })}
/>
</CardSection>
<CardSection>
<Input
secureTextEntry
placeholder='password'
label='Password :'
value={this.state.password}
onChangeText={password => this.setState({ password })}
/>
</CardSection>
<Text style={styles.errorTextStyle}>{this.state.error}</Text>
<CardSection style={{ flexDirection: 'column' }}>
{this.renderButton()}
</CardSection>
</Card>
</View>
);
}
}
const styles = {
errorTextStyle: {
fontSize: 20,
color: 'red',
alignSelf: 'center',
borderColor: 'white',
}
};
export default LoginForm;
The other component's code:
import React from 'react';
import { ActivityIndicator, View } from 'react-native';
// eslint-disable-next-line arrow-body-style
const Spinner = (size) => {
return (
<View style={styles.spinnerStyle}>
<ActivityIndicator size={size || 'large'} />
</View>
);
};
const styles = {
spinnerStyle: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
};
export { Spinner };
I ran the above code and on the expo app on android, it crashed and on ios it didn't crash but displayed the above mentioned error on the red screen.
Did you used "this.props.prop" to access the props, if so, an stateless component doesn't have the "this.props" property, instead you should pass the props like this
In your login screen use this normally
if (this.state.loading) {
return <Spinner prop="small" />;
}
In your component use this
const Spinner = (prop) => {
return (
<View style={styles.spinnerStyle}>
<ActivityIndicator size=prop />
</View>
);
};

react native - undefined is not an object(evaluating 'password.toString')

So, basically, I have two JavaScript files, in one of them there's a function that authenticates to an API and the other one is the login screen running in the emulator. When I try to authenticate, I get the error:
undefined is not an object (evaluating 'password.toString')
This is the login screen file:
import React, {Component} from 'react';
import {View, Text, TextInput, TouchableOpacity} from 'react-native';
import styles from './login-styles';
import {auth} from '../../fetches/auth';
class LoginBox extends Component {
constructor(props) {
super(props)
this.state = {
username: '',
password: ''
}
}
render = () => {
return(
<View style={styles.box}>
<View style={styles.header}>
<Text style={{fontSize: 28}}>Bem-vindo ao PostBag v 0.0.2</Text>
</View>
<View styles={styles.app}>
<TextInput style={styles.square}
keyboardType="numeric"
placeholder='Insira sua matrúcla'
onChangeText={(text) => this.setState({username: text})}
value={this.state.username}
/>
<TextInput style={styles.square}
secureTextEntry
placeholder='Insira sua senha'
onChangeText={(text) => this.setState({password: text})}
value={this.state.password}
/>
<TouchableOpacity
style={styles.button}
onPress={() => auth((this.state.username, this.state.password))}
>
<Text style={styles.buttonTxt}>POST</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
export default LoginBox;
This is the authentication function:
import {Alert} from 'react-native';
export function auth(username, password) {
fetch('https://suap.ifrn.edu.br:443/api/v2/autenticacao/token/',
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-csrftoken': 'NDML6yy6HgTUIoypfWMZHMKZ32lgJf5PsNolVnLgewanw5YM4rqwkuvgkyAhEYEA'
},
body: JSON.stringify({
username: username.toString(),
password: password.toString()
})
}).then(function(response) {
var json = response.json()
json.then((data) => {
token = data.token
if (typeof token === 'undefined') {
Alert.alert('Não foi possível fazer login')
}
else {
Alert.alert('Login feito com sucesso')
}
})
})
}
I would really appreciate if anyone could help me with that. Everything that I tried did not work.
I think, because of that password or username is null or undefined at that moment. You can check if they are defined and they are strings as below,
body: JSON.stringify({
username: typeof username === 'string' ? username.toString() : '',
password: typeof password === 'string' ? password.toString() : ''
})
and your view should be changed as follow,
onPress={() => auth(this.state.username, this.state.password)}
Delete extra brackets from onPress.
auth(this.state.username, this.state.password)
Change this
<TouchableOpacity
style={styles.button}
onPress={() => auth((this.state.username, this.state.password))}
>
to
<TouchableOpacity
style={styles.button}
onPress={() => auth(this.state.username, this.state.password)}
>
Also, whenever you're accessing objects with dot operator (.toString()), it's safe to check if the object is present in the first place.
So it's a good idea to convert this
body: JSON.stringify({
username: username.toString(),
password: password.toString()
})
to
body: JSON.stringify({
username: username && username.toString(),
password: password && password.toString()
})

Firebase unsupported browser

I'm using firebase for my react-native application. I don't know what happen when i trying to sign in using firebase authentication this error show. But, Yesterday it's not happen in my application. I don't know why it happened. Please help me i'm stuck right now.
Error image is on link below
this is my source code:
import React, { Component } from 'react';
import {
Text,
View,
TouchableOpacity,
TextInput,
Image,
Button,
AsyncStorage
} from 'react-native';
import FBSDK, { LoginButton, AccessToken } from 'react-native-fbsdk';
import { GoogleSignin, GoogleSigninButton } from 'react-native-google-signin';
import styles from '../components/style.js';
import firebase from '../components/Firebase.js';
export default class Signin extends Component {
constructor(){
super();
this.state={
email:'',
password: ''
}
}
componentWillMount() {
GoogleSignin.hasPlayServices({ autoResolve: true }).then(() => {
GoogleSignin.configure ({
webClientId: '678031332619-ol6s25inanfpk0fkudjt5dhdhfd1m9ov.apps.googleusercontent.com'
})
})
.catch((err) => {
console.log("Play services error", err.code, err.message);
})
}
signIn(){
firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then((userData) => {
AsyncStorage.setItem('userData', JSON.stringify(userData))
alert("Sign in Success")
this.props.navigation.navigate('Form');
}).catch((e) => {
alert(e)
})
}
handleSigninGoogle() {
GoogleSignin.signIn().then((user) => {
console.log(user);
}).catch((error) => {
console.log('WRONG SIGNIN', error);
}).done();
}
Signout() {
GoogleSignin.signOut()
.then(() => {
console.log('out');
})
.catch((err) => {
});
}
render() {
console.ignoredYellowBox = ['Remote debugger'];
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<Text style={styles.title}> 41 Studio IT Solutions </Text>
<TextInput
style={styles.loginInput}
onChangeText={(email) => this.setState({email})}
value={this.state.email}
underlineColorAndroid='transparent'
placeholder='Email'
/>
<TextInput
style={styles.loginInput}
onChangeText={(password) => this.setState({password})}
value={this.state.password}
underlineColorAndroid='transparent'
placeholder='Password'
secureTextEntry
/>
<View style={styles.main}>
<TouchableOpacity
style={styles.button}
onPress={this.signIn.bind(this)}
>
<Text style={styles.buttonText}> Sign In </Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => navigate('Register')}
>
<Text style={styles.buttonText}> Register </Text>
</TouchableOpacity>
</View>
<LoginButton
style={styles.facebookButton}
publishPremissions={["publish_actions"]}
onLoginFinished= {(error, result) => {
if(error) {
alert(error);
}
else if (result.isCancelled){
console.log('Cancelled')
}
else {
AccessToken.getCurrentAccessToken().then((data) => {
console.log(data.accessToken.toString())
const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken.toString());
firebase.auth().signInWithCredential(credential).catch((e) => console.log(e))
})
}
}
}
onLogoutFinished={() => console.log("logout")}
/>
<GoogleSigninButton
style={styles.googleButton}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Light}
onPress={this.handleSigninGoogle.bind(this)}/>
<Button onPress={() => this.Signout.bind(this)} title="Signout" />
</View>
);
}
}
UPDATE: firebase#4.5.2 resolved this issue
This is the related issue, assuming you are using firebase#4.5.1
https://github.com/firebase/firebase-js-sdk/issues/223
Until a newer version is release, quick fix is to downgrade to 4.5.0

Categories

Resources