So for my college project, I need to make an app that can fetch data from a server and log in to the user.
for the login functional component this is the code that i have used,
const login = () =>{
let number= this.State.number;
if(number.length==0){
alert("Required Field is Missing");
}
else{
let api="http://127.0.0.1/Project18/login.php";
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
let Data = {
number:number,
};
fetch(api,{
method:'GET',
headers: headers,
body: JSON.stringify(Data)
})
.then((response) =>response.json())
.then((response)=>{
alert(response[0].Message);
})
.catch((error) => {
alert("Error" error);
})
}
}
function Login(props) {
const [text, setText] = useState('');
return (
<View>
<TextInput
style={{width:200,margin:10}}
placeholder="Enter Phone Number"
placeholderTextColor={"tomato"}
onChangeText={number => setText(number)}
defaultValue={text}
></TextInput>
<Button
title="Login"
style={styles.loginButton}
onPress={login}
>
</Button>
<Text>Hello</Text>
</View>
);
}
All I need to do is pass the 'setText(number)
' component to the login()
function so that the
let number=
gets its value.
I have very less idea about react native so I can't complete the project. Any help is appreciated.
CodePudding user response:
You can pass the text
state to your login
function as follows.
function Login(props) {
const [text, setText] = useState('');
return (
<View>
<TextInput
style={{width:200,margin:10}}
placeholder="Enter Phone Number"
placeholderTextColor={"tomato"}
onChangeText={number => setText(number)}
defaultValue={text}
></TextInput>
<Button
title="Login"
style={styles.loginButton}
onPress={() => login(text)}
>
</Button>
<Text>Hello</Text>
</View>
);
Then use it in text
as follows.
const login = (text) =>{
let number= text;
...
CodePudding user response:
You can declare the login function inside the Login component.
function Login(props) {
const [text, setText] = useState('');
const login = () => {
let number= this.State.number;
if(number.length==0){
alert("Required Field is Missing");
} else {
let api="http://127.0.0.1/Project18/login.php";
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
let Data = {
number:number,
};
fetch(api,{
method:'GET',
headers: headers,
body: JSON.stringify(Data)
})
.then((response) =>response.json())
.then((response)=>{
alert(response[0].Message);
// use setText() here
})
.catch((error) => {
alert("Error" error);
})
}
};
return (
<View>
<TextInput
style={{width:200,margin:10}}
placeholder="Enter Phone Number"
placeholderTextColor={"tomato"}
onChangeText={number => setText(number)}
defaultValue={text}
></TextInput>
<Button
title="Login"
style={styles.loginButton}
onPress={login}
>
</Button>
<Text>Hello</Text>
</View>
);