Home > Mobile >  React Native - why do functions trigger automaticly?
React Native - why do functions trigger automaticly?

Time:04-24

Let me start up by saying that i'm just started learning React Native, and for that, i will try to be as explicite as possible.

Context:

i'm trying to create a simple sign in/sign up page, i have a home screen that contains 2 Inputs with React State (userName and password) that i need to pass to a service when i press on a button, so the code look like this :
function HomeScreen(props) {
  const [userName, onChangeUserNameText] = React.useState(null);
  const [password, onChangePasswordText] = React.useState(null);
  ...
  return (
        <TextInput 
          ...
          onChangeText={onChangeUserNameText}
          value={userName}
        />
        <TextInput
          ...
          onChangeText={onChangePasswordText}
          value={password}
        />
        <Button
          ...
          onPress={SignIn(userName, password)}
        />
    )

the SignIn(...) method is exported from another file that i called home.service that should handle the communiation between my home screen and the API calls, i also put some logs in that function.

Problem:

for some reason, whenever i load the application, or updated any of my inputs, the function that should be executed when i press on the sing in button is getting executed

on load

enter image description here

on Change Text

enter image description here

what am i missing here ?

Edit/Conclusion :

Tank you @Robin Zigmond, the porblem was as this gentelman said, in the way i called my functions in the onPress event:

<Button
    ...
    onPress={() => SignIn(userName, password)}
/>

CodePudding user response:

You need to add a callback, otherwise SignIn will keep executing:

function HomeScreen(props) {
  const [userName, onChangeUserNameText] = React.useState(null);
  const [password, onChangePasswordText] = React.useState(null);
  ...
  return (
        <TextInput 
          ...
          onChangeText={onChangeUserNameText}
          value={userName}
        />
        <TextInput
          ...
          onChangeText={onChangePasswordText}
          value={password}
        />
        <Button
          ...
          onPress={() => SignIn(userName, password)}
        />
    )
}
  • Related