Home > Net >  how to pass input values to a funtion in react native
how to pass input values to a funtion in react native

Time:12-07

I have 2 inputs email and name which has default values. I am trying to pass the values to a function called getalldata. Every time I console.log(), I get undefined as result. I am new to native so pls help.

export default function Signupfor(props) {

  const [email, setEmail] = useState();
  const [name, setName] = useState();


  function getAlldata() {
 
    console.log(name,email);
  
  }

  const {userInfo, log} = props?.route?.params;
  console.log(log.name);
  return (
    <View style={styles.prheight}>
      <View style={styles.form}>
    
       
        <TextInput
          onChangeText={newText => setName(userInfo.user.name)}
          style={styles.input}
          label="Name"
          defaultValue={userInfo.user.name}
         />
         <TextInput
          style={styles.input}
          label="Email"
          defaultValue={userInfo.user.email}
          onChangeText={newText => setEmail(userInfo.user.name)}
        />
      <View style={styles.button}>
        <Button
          title="Lets Go"
          type="submit"
          onPress={() => getAlldata()}
        />
      </View>

CodePudding user response:

on changeText will only run when you input/change something in input

const [email, setEmail] = useState();
  const [name, setName] = useState();

    useEffect(() => {
    
    const {userInfo, log} = props?.route?.params;
    
     setEmail(userInfo?.email)
    setName(userInfo?.name)
    
    },[props?.route?.params])

and int render method

<TextInput
          onChangeText={newText => setName(newText)}
          style={styles.input}
          label="Name"
          defaultValue={userInfo.user.name}
         />
         <TextInput
          style={styles.input}
          label="Email"
          defaultValue={userInfo.user.email}
          onChangeText={newText => setEmail(newText)}
        />

CodePudding user response:

you can set value as default also

const {userInfo, log} = props?.route?.params;

const [email, setEmail] = useState(userInfo.user.email); const [name, setName] = useState(userInfo.user.name);

<TextInput
      onChangeText={newText => setName(userInfo.user.name)}
      style={styles.input}
      label="Name"
      value={name}
      defaultValue={userInfo.user.name}
     />
     <TextInput
      style={styles.input}
      label="Email"
      value={email}
      defaultValue={userInfo.user.email}
      onChangeText={newText => setEmail(userInfo.user.name)}
    />
  • Related