React Native React Thunk activating upon the initial rendering of a component and every time a key is pressed in an input field

As a newcomer to react, react-native, react-redux, and react-thunk, I find myself facing a strange issue that is puzzling me.

The sign-in component I have implemented uses a thunk for user authentication. I have mapDispatchToProps and applied it to the component, but for some reason, every time the component renders, the thunk is triggered. Additionally, each keypress in either input field also triggers the thunk, leading to multiple calls to the authentication API that all end up failing.

What could be causing this unexpected behavior?

const SignIn = ({navigation, signIn}: any): React.ReactElement => {
  const [username, setUsername] = React.useState<string>('');
  const [password, setPassword] = React.useState<string>('');
  const [passwordVisible, setPasswordVisible] = React.useState<boolean>(false);

  const onForgotPasswordButtonPress = (): void => {
    navigation && navigation.navigate('Forgot Password');
  };

  const onPasswordIconPress = (): void => {
    setPasswordVisible(!passwordVisible);
  };

  const passwordInput = useRef() as React.MutableRefObject<any>;

  return (
    <KeyboardAvoidingView>
      <ImageOverlay
        style={styles.container}
        source={require('../assets/images/image-background3.jpg')}>
        <SafeAreaView style={styles.container}>   
          <View style={styles.formContainer}>
            <Input
              status="control"
              placeholder="Username"
              autoCapitalize={'none'}
              autoCompleteType={'off'}
              autoCorrect={false}
              autoFocus={false}
              icon={PersonIcon}
              value={username}
              onChangeText={setUsername}
              returnKeyType={'next'}
              blurOnSubmit={false}
              onSubmitEditing={() => passwordInput.current.focus()}
            />
            <Input
              ref={passwordInput}
              style={styles.passwordInput}
              status="control"
              placeholder="Password"
              autoCapitalize={'none'}
              autoCompleteType={'off'}
              autoCorrect={false}
              icon={passwordVisible ? EyeIcon : EyeOffIcon}
              value={password}
              secureTextEntry={!passwordVisible}
              onChangeText={setPassword}
              onIconPress={onPasswordIconPress}
              onSubmitEditing={() => signIn(username, password)}
            />
            <View style={styles.forgotPasswordContainer}>
              <Button
                style={styles.forgotPasswordButton}
                appearance="ghost"
                status="control"
                onPress={onForgotPasswordButtonPress}>
                Forgot your password?
              </Button>
            </View>
          </View>
          <Button
            style={styles.signInButton}
            status="control"
            size="large"
            disabled={username.length === 0 || password.length === 0}
            onPress={signIn(username, password)}>
            Sign In
          </Button>
        </SafeAreaView>
      </ImageOverlay>
    </KeyboardAvoidingView>
  );
};

const mapDispatchToProps = (dispatch: any) => ({
  signIn: (username: string, password: string) =>
    dispatch(signInThunk(username, password)),
});

export const SignInScreen = connect(
  null,
  mapDispatchToProps,
)(SignIn);

thunk:

export const signInThunk = (username: string, password: string) => {
  return async (dispatch: any) => {

    try {
      dispatch(isLoading(true));

      const userData = await fetch(Providers.auth, {...})
        .then(response => response.json())
        .then(() => dispatch(isLoading(false)));

      if(userData.token){
       dispatch(signInAction(userData.token));
       dispatch(updateProfileAction(userData));
      }

      dispatch(isLoading(false));
    } catch (error) {
      console.error(error);
    }
  };
};

Answer №1

One common mistake to watch out for is:

onPress={signIn(username, password)}

Instead, you should modify it to:

onPress={() => signIn(username, password)}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Harness the power of the Node.js Path module in conjunction with Angular 6

I'm currently facing an issue with utilizing the Path module in my Angular 6 project. After some research, I came across a helpful post detailing a potential solution: https://gist.github.com/niespodd/1fa82da6f8c901d1c33d2fcbb762947d The remedy inv ...

Troubleshooting the Hide/Show feature in React Native

As a newcomer to React Native development, I am attempting something simple. Within a React Class extending Component, I have 4 components <TouchableOpacity>. In the render function, my goal is to hide three of these components while pressing on one ...

Utilizing the React TypeScript useContext hook with useReducer for state management

I'm struggling to identify the type error present in this code snippet import React from 'react'; interface IMenu { items: { title: string, active: boolean, label: string }[] } type Action = | { type: 'SET_ACTIVE&a ...

Tips for ensuring a function in Angular is only executed after the final keystroke

I'm faced with the following input: <input type="text" placeholder="Search for new results" (input)="constructNewGrid($event)" (keydown.backslash)="constructNewGrid($event)"> and this function: construct ...

How can dependencies for an entire class or module be mocked in the mocha ecosystem similar to jest.mock?

I am currently working on unit testing a module that resembles the following code structure: import { Countdown } from "./database/orm"; export class PersistentTimer { protected constructor(...) { ... } // To ensure database writing ...

Having trouble getting the Angular 2 quickstart demo to function properly?

Just starting out with Angular 2, I decided to kick things off by downloading the Quickstart project from the official website. However, upon running it, I encountered the following error in the console: GET http://localhost:3000/node_modules/@angular/ ...

Can a JavaScript object be created in TypeScript?

Looking for a way to utilize an existing JavaScript "class" within an Angular2 component written in TypeScript? The class is currently defined as follows: function Person(name, age) { this.name = name; this.age = age; } Despite the fact that Java ...

What are the benefits of maintaining a property as non-observable instead of observable in knockout.js?

In my TypeScript project utilizing Knockout.js, I have a class with several properties. One of these properties is 'description', which is not directly tied to the DOM but needs to be used in popups triggered by certain mouse events (such as butt ...

Determine the accurate data type while iterating through a for loop

I am facing an issue where I have around 40 unique actions defined, all with the same parameters except for each being provided with a different schema which is causing the problem type ActionName = 'replaceText' | 'replaceImage'; type ...

React component stuck in endless loop due to Intersection Observer

My goal is to track the visibility of 3 elements and update state each time one of them becomes visible. Despite trying various methods like other libraries, useMemo, useCallback, refs, etc., I still face challenges with my latest code: Endless loop scenar ...

Tips and tricks for accessing the state tree within effects in @ngrx/effects 2.x

I am currently in the process of migrating my code from version 1.x to 2.x of @ngrx/effects. Previously, in version 1.x, I was able to access the state tree directly within an effect: constructor(private updates$: StateUpdates<AppState>) {} @E ...

Encountering difficulties in loading my personal components within angular2 framework

I encountered an issue while trying to load the component located at 'app/shared/lookup/lookup.component.ts' from 'app/associate/abc.component.ts' Folder Structure https://i.stack.imgur.com/sZwvK.jpg Error Message https://i.stack.img ...

"Creating an array object in the state of Reactjs - a step-by-step

As I am delving into the world of ReactJS, I am learning about changing state within this framework. One challenge I encountered was initializing an array object in state with an unknown length and updating it later using setState. Let me share the snippet ...

The compiler option 'esnext.array' does not provide support for utilizing the Array.prototype.flat() method

I'm facing an issue with getting my Angular 2 app to compile while using experimental JavaScript array features like the flat() method. To enable these features, I added the esnext.array option in the tsconfig.json file, so the lib section now includ ...

The inRequestScope feature seems to be malfunctioning and is not functioning as intended

Need help with using inRequestScope in inversifyJS For example: container.bind<ITransactionManager>(Types.MysqlTransactionManager).to(MysqlTransactionManager).inRequestScope() ... container.get<ITransactionManager>(Types.MysqlTransactionMana ...

What is the best way to extract information from a button and populate a form in AngularCLI?

I am currently attempting to enhance my Angular App by using a button to transfer information to a form upon clicking, rather than the traditional radio buttons or select dropdowns. My objective is to incorporate HTML content into the button (such as Mat-I ...

Maintaining the "Date" value in React Native DatePickerIOS when returning from other pages

In my scenario, I am using the DatePickerIOS component. The example in the documentation initializes a new Date() and uses state to store and update the Date value. However, when navigating to another page and returning, the time changes and I find myself ...

Using Next.js and Tailwind CSS to apply a consistent pseudo-random color class both on the server and client side

I am faced with a challenge on my website where I need to implement different background colors for various components throughout the site. The website is generated statically using Next.js and styled using Tailwind. Simply selecting a color using Math.ra ...

The firebase-generated observable is causing the notorious differ error as it is not iterable

Hey there, I'm encountering an issue that's preventing the route from rendering correctly. I initially thought that unwrapping an observable into an iterable using the async pipe would solve it, but this error indicates otherwise. Sometimes obser ...

Leverage the Nuxeo client SDK with Angular 6 for seamless integration with RESTClient in

Looking to integrate the Nuxeo ClientSdk with my Angular 6 client to consume its REST API, but facing issues due to the lack of typescript definitions for this JavaScript package. Tried importing the library into my project using the following code snippe ...