Unable to cancel the setTimeout function by using clearTimeout as the value appears to be null for unknown reasons

Within my react-native application, I am attempting to halt the execution of a setTimeout function by utilizing clearTimeout. The instance of setTimeout is stored in a global variable.

let timeoutId: any = null;

    const doOtp = () => {
        if(canSendOtp) {
            setCanSendOtp(false);

            timeoutId = setTimeout(() => { // a numeric value is present here
                showNotificationMessage("You can request OTP again")
                setCanSendOtp(true)
            }, SEND_OTP_TIME_CONSTRAINTS)

           // additional logic for doOtp
        }
        else {
            showNotificationMessage("Please wait " + (SEND_OTP_TIME_CONSTRAINTS / 1000) + " seconds before trying again")
        }
    }

However, when attempting to stop the setTimeout using clearTimeout, I encounter an issue where the value of timeoutId is null. This occurrence is puzzling to me.

const doLogin = () => {
issueToken(LOGIN_GRANT_TYPE, LOGIN_CLIENT_ID, LOGIN_CLIENT_SECRET, phoneNumber, otp)
    .then(res => { 
        
        console.log('timeoutId !== null' + timeoutId !== null)
        if(timeoutId !== null) { // the value at this point is null - the reason remains unclear
            clearTimeout(timeoutId)
        }

        store().dispatch(setTokenValidity(res))
    })
    .catch(err => {
        showNotificationMessage('Error, something went wrong check logs.')
        console.log("issueToken error: " + JSON.stringify(err))
    });

}

Answer №1

TASK

The function setCanSendOtp(true) is responsible for updating the state, which in turn resets the timeout to null.

RESOLUTION

To resolve this issue, it is recommended to store the timeout in a Ref. Ref values persist throughout re-renders and state updates.

const timeoutId:any = React.useRef(null);

const handleOtp = ()=>{
        if(canSendOtp) {
            setCanSendOtp(false);

            timeoutId.current = setTimeout(() => { // it has here a numeric value
                showNotificationMessage("You can request OTP again")
                setCanSendOtp(true)
            }, SEND_OTP_TIME_CONSTRAINTS)

           // rest of handleOtp logic
        }
        else {
            showNotificationMessage("Please wait " + (SEND_OTP_TIME_CONSTRAINTS / 1000) + " seconds before trying again")
        }
    }

const handleLogin = () => {
issueToken(LOGIN_GRANT_TYPE, LOGIN_CLIENT_ID, LOGIN_CLIENT_SECRET, phoneNumber, otp)
    .then(res => { 
        
        if(timeoutId.current !== null) {
            clearTimeout(timeoutId.current)
        }

        store().dispatch(setTokenValidity(res))
    })
    .catch(err => {
        showNotificationMessage('Error, something went wrong check logs.')
        console.log("issueToken error: " + JSON.stringify(err))
    });

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

The Express Electron framework does not support importing local JavaScript files

Despite my extensive search before flagging this as a duplicate, I have not been able to find the solution I need. I am encountering issues with using express and electron. Everything runs smoothly when I execute npm start (the start script in package.jso ...

Utilizing ng-model to control the visibility of a label or anchor tag

Here is the code snippet I am working with: <div class="tabs DeliveryRightDiv"> <label class="selected"><a>One</a></label> <label> <a>Two</a> </label> <label> ...

Having trouble getting the onclick function to work in order to switch out the images

This is the HTML code that I used Here is the JavaScript code, but the onclick function seems to not be working ...

What is the process for adjusting the position following the modification of a table value in React?

In my React UI, I have set up two text fields for entering values. After saving the values, they are displayed in a table below (designed with antd). When I click on a record in the table to edit it, I want the data from that record to populate the text f ...

The Proper Way to Position _app.tsx in a Next.js Setup for Personalized App Configuration

I've been working on a Next.js project and I'm currently trying to implement custom app configuration following the guidelines in the Next.js documentation regarding _app.tsx. However, I'm encountering some confusion and issues regarding the ...

Tips for incorporating HTML code within a select option value?

I am working with AngularJS to create a Visual Composer for a website. One feature I want to incorporate is the ability to add HTML code based on the selection made in a dropdown menu. However, I am struggling to figure out how to include the HTML within t ...

Here is a unique version: "In Javascript, users can trigger the function this.Something() from within this.img.onload by

I have some code that looks like this... Thing function () { var img = new Image; DoSomeStuff function() { //Code here that relies on my image being loaded... }; InitMe function(src) { this.img.onLoad = this.DoSomeStuff; ...

To interact with a specific cell in a table using Protractor, simply click

I have a dataset containing various elements such as images, text, and numbers. I am struggling to click on a specific text within the dataset. As someone new to e2e testing with Protractor, any assistance would be greatly appreciated. I specifically need ...

Disable, Hide, or Remove Specific Options in a Single Dropdown Selection

A challenge I am facing involves creating a form with multiple select options that need to be ranked by the user from 1-8. However, I am encountering some difficulties in hiding, removing, or disabling certain select options. Below is an excerpt from my f ...

Building a remote shell using Node.js with the ability to interpret control sequences

Currently, I am working on developing a remote shell using Node.js. Here's the code that I have implemented so far : Client var net = require('net'); var client = net.connect({port: 1234}, function(){ process.stdin.pipe(client); clien ...

Create an HTML table to view JSON data from a cell on a map

Looking to transform the JSON data into a table by organizing the information based on supplier and product. Below is the JSON input and code snippet: $(document).ready(function () { var json = [{ "Supplier": "Supplier1", "Product": "O ...

What is preventing me from passing a JSON array as data in a GET request using jQuery Ajax?

When sending a get request like the one below: $.ajax({ url: 'http://localhost:8000/api/points/', contentType:"application/json", dataType: "json", data: JSON.stringify({"content_type":content_type,"object_id":object_id}), t ...

Obtaining the HTML content of a div element that has been retrieved through an AJAX request to a PHP script

My challenge is to fetch a dropdown menu from a server and then manipulate it using jQuery after loading. Although everything loads correctly, I am unable to interact with the dropdown items because they were dynamically added post AJAX response instead of ...

Utilizing $resource within a promise sequence to correct the deferred anti-pattern

One challenge I encountered was that when making multiple nearly simultaneous calls to a service method that retrieves a list of project types using $resource, each call generated a new request instead of utilizing the same response/promise/data. After doi ...

What is the reason for the JavaScript TypeError (undefined) being triggered when this object is used within a function?

I have defined a new object like this: function node(){ this.tag = null; this.Tdata = []; this.Tchilds = []; } Now, I am trying to use this object in a function: function Validate(root /*Ass ...

Tips for navigating through lengthy webpages using the jQuery onepage-scroll plugin

I recently came across a fantastic plugin called onepage-scroll that almost perfectly fits my requirements. However, I have encountered an issue. Some of my pages, defined within <section> tags, are larger than a single screen. Is there a way to cust ...

Display a pop-up window using window.open and automatically print its contents using window.print upon loading

I am trying to open a new window with some HTML content and then automatically print it. Here is the code snippet I have: var windowObject = window.open('','windowObject','arguments...'); windowObject.document.write("<html ...

Utilize the composition API in Vue.js 3 to call a function and pass in a parameter

I'm having trouble calling a function from another component. When I click on a button in my parent component, formTelemarketing(), it should send data to my other component nAsignedCalls() and call the function getCalls(param) in that component. Thi ...

Strategies for extracting the type argument from a nested property and transforming it into a different value

I’m struggling to find the right way to frame my question, so I’ll provide an example of what I need help with. Let's assume I have the following object: const obj = { one: 'some string', two: new Set<string>(), }; Now, I wan ...

Adjusting color schemes for Twitter Bootstrap Tooltips according to their placement

I have been attempting to customize the colors of tooltips (specifically from Twitter Bootstrap), but I am encountering some difficulties. While changing the default color was straightforward, altering the colors for .tooltip and its related definitions ha ...