0

Let me start up by saying that i 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)}
/>
El.K Ibrahim
  • 53
  • 1
  • 8
  • 2
    `SignIn(userName, password)` executes the function, so of course it gets executed every time your component renders. What you need is `onPress={() => SignIn(userName, password)}` – Robin Zigmond Apr 23 '22 at 15:49
  • Does this answer your question? [React: onClick handler is getting called on every render?](https://stackoverflow.com/questions/41688366/react-onclick-handler-is-getting-called-on-every-render) – Robin Zigmond Apr 23 '22 at 15:53
  • You are a life saviour ! – El.K Ibrahim Apr 23 '22 at 15:55

1 Answers1

2

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)}
        />
    )
}
RamaProg
  • 1,106
  • 7
  • 15