Connect PHP api to React-Native for User Login
Get the solution ↓↓↓I'm trying to connect my PHP api to my react-native project so that the login page functions allowing the user to login. I also want the user to be stayed logged in once they have logged in, that's why I am using AsyncStorage. I've also tried to connect to my database using node.js and express but have not been able too. Can someone guide me and show me where I'm going wrong. Also is there a way to have 2 onChangeText for TextInput because the first onChangeText stops working when I try and implement a second.
import React,{Component, useState } from 'react';
import {View,TextInput, StatusBar, Text, StyleSheet,Button, TouchableOpacity, Dimensions, Platform} from 'react-native';
import * as Animatable from 'react-native-animatable';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import Feather from 'react-native-vector-icons/Feather';
import LinearGradient from 'react-native-linear-gradient';
import { AuthContext} from '../components/context';
import AsyncStorage from '@react-native-async-storage/async-storage';
UserLoginFunction = () =>{
const { email } = this.state ;
const { password } = this.state ;
fetch('https://localhost/SparXCard/api/login.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password
})
}).then((response) => response.json())
.then((responseJson) => {
// If server response message same as Data Matched
if(responseJson === 'Data Matched')
{
AsyncStorage.setItem('user', res.user);
//Then open Profile activity and send user email to profile activity.
this.props.navigation.navigate('HomeScreen', { Email: email });
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
const SignInScreen = ({navigation}) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [data, setData] = React.useState({
email:'',
password: '',
check_textInputChange: false,
secureTextEntry: true
});
const {signIn} = React.useContext(AuthContext);
const textInputChange = (val) => {
if(val.length != 0) {
setData({
...data,
email: val,
check_textInputChange: true
});
} else {
setData({
...data,
email: val,
check_textInputChange: false
});
}
}
const handlePasswordChange = (val) => {
setData({
...data,
password: val
});
}
const updateSecureTextEntry = () => {
setData({
...data,
secureTextEntry: !data.secureTextEntry
})
}
const componentDidMount = () => {
this._loadInitialState().done();
}
const _loadInitialState = async () => {
var value = await AsyncStorage.getItem('user')
if(value !== null){
this.props.navigation.navigate('HomeScreen')
}
}
/*User Interface*/
return(
<View style={styles.container}>
<StatusBar backgroundColor='#009387' barStyle='dark-content'/>
<View style={styles.header}>
<Text style={styles.text_header}>Welcome!</Text>
</View>
<Animatable.View style={styles.footer}
animation="fadeInUpBig"
>
<Text style={styles.text_footer}>Email</Text>
<View style={styles.action}>
<FontAwesome name="user-o" color="#ffdf2b" size={20} />
<TextInput
placeholder="Your Email"
placeholderTextColor = "#7a6b02"
style={styles.textInput}
autoCapitalize="none"
/* first onChangeText stops working when second once is implemented */
onChangeText={(val)=>textInputChange(val)}
onChangeText={email => setEmail(email)}
/>
{data.check_textInputChange ?
<Animatable.View animation="bounceIn">
<Feather
name="check-circle"
color="green"
size={20}
/>
</Animatable.View>
: null}
</View>
<Text style={[styles.text_footer, {marginTop: 45}]}>Password</Text>
<View style={styles.action}>
<FontAwesome name="lock" color="#ffdf2b" size={20} />
<TextInput
placeholder="Your Password"
placeholderTextColor = "#7a6b02"
secureTextEntry={data.secureTextEntry ? true : false}
style={styles.textInput}
autoCapitalize="none"
onChangeText={(val)=> handlePasswordChange(val)}
onChangeText={password => setPassword(password)}
/>
<TouchableOpacity onPress={updateSecureTextEntry}>
{data.secureTextEntry ?
<Feather
name="eye-off"
color="grey"
size={20}
/>
:
<Feather
name="eye"
color="grey"
size={20}
/> }
</TouchableOpacity>
</View>
<View style={styles.button}>
<TouchableOpacity style={styles.signIn} onPress={this.login} >
<LinearGradient colors={['#ffdf2b', '#cfb504']} style={styles.signIn}>
<Text style={[styles.textSign,{color:'#161616'}]}>Sign In</Text>
</LinearGradient>
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate('SignUpScreen')} style={[styles.signIn,
{ borderColor: '#ffdf2b', borderWidth:1, marginTop:20}]}>
<Text style={[styles.textSign,{color:'#ffdf2b'} ]}>Sign Up</Text>
</TouchableOpacity>
</View>
</Animatable.View>
</View>
);
};
/*
login = () => {
fetch('http://localhost:3000/users',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type' : 'application/json',
},
body: JSON.stringify({
email: this.email,
password: this.password,
})
})
.then((response) => response.json())
.then((res) => {
alert(res.message)
if (res.success === true) {
AsyncStorage.setItem('user', res.user);
this.props.navigation.navigate('HomeScreen');
}
else{
alert(res.message)
}
})
.done();
} */
export default SignInScreen;
My PHP email and login api.
//Define your host here.
$HostName = "localhost";
//Define your database name here.
$DatabaseName = "users";
//Define your database username here.
$HostUser = "root";
//Define your database password here.
$HostPass = "root";
// Creating connection.
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json,true);
// Populate User email from JSON $obj array and store into $email.
$email = $obj['email'];
// Populate Password from JSON $obj array and store into $password.
$password = $obj['password'];
//Applying User Login query with email and password match.
$Sql_Query = "select * from user where email = '$email' and password = '$password' ";
// Executing SQL Query.
$check = mysqli_fetch_array(mysqli_query($con,$Sql_Query));
if(isset($check)){
$SuccessLoginMsg = 'Data Matched';
// Converting the message into JSON format.
$SuccessLoginJson = json_encode($SuccessLoginMsg);
// Echo the message.
echo $SuccessLoginJson ;
}
else{
// If the record inserted successfully then show the message.
$InvalidMSG = 'Invalid Username or Password Please Try Again' ;
// Converting the message into JSON format.
$InvalidMSGJSon = json_encode($InvalidMSG);
// Echo the message.
echo $InvalidMSGJSon ;
}
mysqli_close($con);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: trying to access array offset on value of type bool
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.