Why does the arrow function get executed right away once it is wrapped?

Currently, I am working on developing an app using react native. The goal is to have the screen automatically advance to the next one if there is no touch response within 5 seconds.

I have implemented a function where pressing a button or entering text will reset the timer back to 5 seconds. Despite this, the function seems to be triggered as soon as the button is pressed. How can I fix this issue? Any advice would be greatly appreciated.

//ReceiptScreen
...
componentWillUnmount() {
    this._isMounted = false;
    clearTimeout(this.nextScreenTimer);
}

handleSendPress = () => {
    if (isValidEmail(this.state.email)) {
      this.props.sendEmailReceipt(this.state.email, this.props.order);
    } else {
      Alert.alert(
        null,
        [
          {
            text: 'close',
            onPress: () => null,
          },
        ],
        {cancelable: true},
      );
    }
};

handleScreenTimeout = func => {
    console.log('what', func);
    clearTimeout(this.nextScreenTimer);
    this.nextScreenTimer = setTimeout(() => {
      this.handlePressClose();
    }, 5000);
    func();
};

componentDidMount() {
    this.nextScreenTimer = setTimeout(() => {
      this.handlePressClose();
    }, 5000);
}
....

render() {
....
            <InputButton
              placeholder={'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f4a574e425f434a6f48424e4643014c4042">[email protected]</a>'}
              value={this.state.email}
              onChangeText={text => this.setState({email: text})}
              loading={this.props.isEmailReceiptFetching}
              onPress={this.handleScreenTimeout(this.handleSendPress)}
            />
}

Answer №1

In order to make the necessary change to the onPress handler, you will need to modify it as shown below:

onPress={() => this.handleScreenTimeout(this.handleSendPress)}

This way, you are creating a function that calls your desired function inside of it.

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

Typescript: Mongoose encountered an error when trying to convert value to ObjectId for the specified path "_id"

Whenever I intentionally use postman to request a wrong product ID, the application crashes. Cause The error is not being caught by my error-handler middleware. Route /* retrieves a single product */ router.get("/:id", async (req: Request, res: Respons ...

`CSS Content Placeholder Issue When Used Alongside JavaScript`

Let me explain a bit, I have a master page named UserProfile.master which has a content placeholder linked to UserProfileWall.aspx. Now, I am trying to incorporate some additional JavaScript and a second CSS file in the userprofilewall page. However, whene ...

The terminal in VS CODE is not able to detect Stripe

When I attempt to run the command 'stripe listen' in the VS Code terminal, an error is thrown: The term 'stripe' is not recognized as the name of a cmdlet, function, script file, or operable program. Please check the spelling of the ...

Using jQuery to retrieve a dynamic element by its ID and store it in an array

I am currently in the process of developing a classifieds website. The search page will feature multiple product cards, each of which can have multiple images. In order to showcase these images, I am implementing a slider using a jQuery library called bxsl ...

What are some effective approaches to consider when developing AngularJS directives?

How can one ensure best practices are followed when creating angularJS directives? Some key points to consider: The optimal size of the link function Best practices for what to do and what not to do in the link function The proper usage of scope.$apply ...

Unleash the full power of Angular Components by enhancing them with injected

I am facing a challenge with handling the destruction event of an Angular component in my external module that provides a decorating function. I've run into issues trying to override the ngOnDestroy() method when it includes references to injected ser ...

Webpack: Live reloading is not functioning properly, however the changes are still successfully compiling

Could someone help me understand why my React application, set up with Webpack hot reload, is not functioning properly? Below is the content of my webpack.config.js: const path = require('path'); module.exports = { mode: 'development&apo ...

Managing multiple ajax requests only functions properly when notifications are raised

I'm looking to efficiently transfer data to the server from multiple lists on a page by using ajax calls to process the information in PHP. My code iterates through each list with the class "dd" and sends the ajax data one by one. Everything works smo ...

I was surprised to find something other than a gulp folder in the node_modules directory after running npm install gulp --save-dev

Seeking some guidance on my process - can someone point out if I am making a mistake? Downloaded Node from their official website Global installation of Gulp (npm install --global gulp) Created a folder and initiated it by running (npm init), which gene ...

Steps to creating a nested function

I'm still learning the ropes of Javascript, and I've been working on creating a personal library to streamline my coding process. Here's the code snippet I've come up with. function myLibrary() { let _this = this; this.addString = ...

Leveraging Laravel Blade and Ajax for lightning-fast searching

Here is my jquery code When running the code, I encountered an issue where Laravel blade did not recognize the $results variable in the foreach statement. Despite the fact that I did not provide the form or route code, they function as expected. The main ...

Error encountered while routing in Node.js

Apologies for the basic nature of this question, but I find myself unable to resolve it on my own. I am currently developing an application that will send messages based on a specific parameter in Json. Below is an excerpt from my app.config.json file: & ...

Please input numbers only into the designated field

I am trying to create an input field in my form that only accepts numbers when pasted into it. For example: If I have some random characters like W123W000 on my clipboard, the input field should only paste 123000. Note: This solution is currently only fu ...

It appears that Serverworker is causing significant delays in processing ajax requests

I'm encountering some performance issues with my PHP app that utilizes a lot of JavaScript for AJAX requests back to the PHP server. I'm currently implementing a service worker to cache content and enable push notifications, but I'm facing d ...

Dynamically populate 7 select boxes with options using JQuery

I have a webpage that includes 14 different dropdown menus, one for each day of the week (Monday to Sunday). Each day has two dropdowns: one for opening time and one for closing time. I used jQuery to populate all 14 dropdowns with a pre-defined list of ho ...

Next.js Pre-rendering Issue: Error encountered when trying to access properties of a null object

Using Next.js for a React application (full code available here.) Encountering an unusual error while running next build, showing errors related to prerendering on five pages: spenc@WhiteBoxu:~/workout-tracker$ next build info - Loaded env from /home/spe ...

I am attempting to utilize the fetch API method to initialize the store's state, but for some reason, it is not functioning properly

Within my store.js file, I have a state called user_data, with its initial method set to fetch_user_data: export default new Vuex.Store({ state: { user_data: util.fetch_user_data('username') ... } located in the util.js file: util. ...

What is the best way to add the ajax response to a specific div element?

The ajax code I'm currently using is designed to retrieve a result from another PHP file. My goal now is to append this result to the corresponding 'preview' div ID. $("#imageform").ajaxForm({ target: '#preview' }).submit(); ...

Experiencing peculiar behavior with the delete keyword in JavaScript

Okay, so here's the deal... var obj = people[0]; obj.oAuthID = null; delete obj.oAuthID; This code snippet returns... { "uuid": "39b2b45f-1dde-4c9a-8765-1bc76f55848f", "oAuthID": null, "date": "2013-10-21T16:48:47.079Z", "updated": "2013-10 ...

Can a `react` app with `mysql` be uploaded to `github`?

I recently created a basic online store with the help of react, node, and mysql. I am considering uploading it to github, but I'm uncertain if I can do so while my database is currently stored on localhost. Any advice? ...