Search code examples
react-nativeuse-statesetstatereact-functional-component

How to pass an useState to a Function from a Funtional Component?


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.


Solution

  • You can declare the login function inside the Login component.

    function Login(props) {
     const [text, setText] = useState('');
    
     const login = () => {
       let number= text;
       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>
    );