简体   繁体   中英

Cannot call function only once in React Native?

I have a React Native project with a GraphQL server. I'm using Apollo Client to get the data from my API. I've created this simple component that takes all of the data needed for registration from the route parameters (form the step-by-step registration) and makes the mutation to create a new store.

export default function AuthRegisterStore({ navigation, route }) {
  const [
    register,
    { loading: validating, error: validationError, data: returnData },
  ] = useMutation(REGISTER, { onError: (e) => Alert.alert(String(e)) });

  const handleRegistration = () => {
    register({
      variables: {
        username: route.params.username,
        password: route.params.password,
        latitude: route.params.latitude,
        longitude: route.params.longitude,
      },
    });
  };

  handleRegistration()

  if (validating) {
    return <Loader />;
  }

  if (validationError) {
    return (
      <View style={styles.container}>
        <Text>Error</Text>
      </View>
    );
  }

  if (returnData) {
    navigation.navigate("Login", { message: "Te logueaste!" });
  }

  return null;
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});

The problem is that the function handleRegistration() is being called again and again, causing an infinite loop. I've tried using useEffect() but it just won't make the API call for some reason. What am I missing?

Yes - handleRegistration() is set up to run on every re-render right now. If you used useEffect , you likely didn't include the dependency array (I'll show you in a second) which is also causing it to run on every re-render. Try this:

useEffect(() => {
  handleRegistration()
}, [])

Note the empty array in useEffect . This tells react to run this just one time. You could omit it (like you may have done) which tells react to run it every time the component re-renders. Or you can pass parameters into the array which react will watch and run when those specific parameters change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM