There was no timeout triggered on the second attempt to retrieve data

I have implemented a login page in React-Native that functions properly when there is an Internet connection. However, I now need to address the scenario where the Internet or server connection is unavailable. My approach to handling this is by utilizing timeouts: the application should attempt to establish a connection, and if unsuccessful after five seconds, display an error message.

To achieve this, I have utilized the following code snippet sourced from here:

export function timeout(
  promise,
  message = 'Request timeout',
  timeout = DEFAULT_TIMEOUT,
) {
  return new Promise((resolve, reject) => {
    const timeoutId = setTimeout(() => {
      console.log('timeout called');
      reject(new Error(message));
    }, timeout);
    promise.then(
      response => {
        clearTimeout(timeoutId);
        resolve(response);
      },
      err => {
        console.log('timeout NOT called');
        clearTimeout(timeoutId);
        reject(err);
      },
    );
  });
}

Within the login page, the function is invoked as follows:

response = await timeout(
   getAccessToken(this.state.username, this.state.password),
  'Unable to connect to the server.',
);

Here, getAccessToken serves as an asynchronous wrapper for fetch. The function performs as expected during the initial login attempt with no Internet connectivity. It correctly waits for five seconds (DEFAULT_TIMEOUT) before displaying the 'Unable to connect to the server' error message. However, upon subsequent login attempts, rather than waiting for the designated time period, a generic 'Network error' is displayed. This behavior can be observed in the logs:

[12:08:44] I | ReactNativeJS ▶︎ timeout called                (first click)
[12:08:49] I | ReactNativeJS ▶︎ timeout NOT called            (second click)

The issue lies in why the timeout fails to trigger on subsequent login attempts, causing the automatic failure of the timeout. What could be causing this problem and how can it be rectified?

Answer №1

Promise objects given back by calling fetch() will be marked as rejected in case of a network failure or an incomplete request.

In situations where there is a network error or misconfiguration of CORS on the server side, the import () task will result in rejection due to a TypeError. Subsequent attempts will promptly transition to the reject state upon encountering the TypeError.

To trigger a timeout once more, execute the fetch() function after reconnecting to the Internet. Turn off the Internet again and rerun the fetch().

IMPORTANT: Promise objects from fetch() do not reject based on HTTP error statuses, even if the HTTP Status Code indicates 404 or 500.

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 value of req.session.returnTo is not defined

I have implemented passport for user authentication using discord oauth2. I want the users to be redirected back to the original page they came from instead of being directed to the home page or a dashboard. Even though I tried saving the URL in the sessi ...

Is there an issue with the JSON data?

"stocksdata" :[{"id":7,"SCRIP":"ASIANPAINT","LTP":3341,"OHL":"BUY","ORB15":"BREAKOUT","ORB30":"NT","PRB":"NA","CAMARILLA& ...

What is the best way to implement a never-ending scrolling grid loader within a scrollable area using Codeigniter?

In my Codeigniter framework and bootstrap installation, I have multiple sub-pages. On one of these pages, I am attempting to implement an infinite scroll loader using a jQuery script from a tutorial found at gridScrollFx.js. Here is the JS file I am using: ...

The response from the Ajax request in jQuery did not contain any content to download

I have a PHP script that generates PDF output successfully when accessed directly. Now, I want to fetch this PDF file using AJAX. In pure JavaScript, the following code snippet works well: var req = new XMLHttpRequest(); req.open("POST", "./api/pd ...

Transform JSON code from JQuery to PHP

Currently, I am in the process of translating a code snippet from JQuery to PHP for performing a json POST request to a remote server. Here is my original Jquery code: $( document ).ready(function() { $('#button').click( function() ...

Utilizing stored data to display multiple markers on Google Maps with Node, MongoDB, Express, and EJS

I've been working on a project that involves passing values from mongodb to the google maps script in order to display multiple markers. While I've been able to load the map successfully, I'm facing difficulties defining my customers and loo ...

The resource-intensive nature of ExpressJs HTTP Streaming is causing my disk space to deplete rapidly

My express server app.get('/data', (_, res) => { const interval = setInterval( () => res.write(`${Math.random().toString()}\n`), 1000 ); res.on('close', () => { clearInterval(interval); ...

In Javascript, when declaring a variable, check if a field is filled and assign its value if so; otherwise, set a default value

In the code snippet below, there are some rows with a nested field value present and some without. I am attempting to assign a value if the field is present, otherwise I want to set it as 'false'. Despite using the double pipe operator to handle ...

Steps to create a toggle feature for the FAQ accordion

I am currently working on creating an interactive FAQ accordion with specific features in mind: 1- Only one question and answer visible at a time (I have achieved this) 2- When toggling the open question, it should close automatically (having trouble with ...

Printing the HTML Template of a widget with multiple loops results in a blank first page being displayed

I have encountered an issue while working with a table and ng-repeat loops in my report widget. The table displays fine on the screen, but when I try to print it, there is always a blank page at the beginning. Interestingly, if I remove the second and thir ...

The issue with ag-grid not displaying data when the column configurations are changed dynamically

I have been working with ag grid to display data in my component. I am fetching data through an API call and dynamically extracting the column names from the response to pass this information to the child component for display. However, the data is not sho ...

Designing a mobile user interface for time intervals

Currently, I am utilizing a datetimepicker for inputting a duration of time within a form. While the UI functions smoothly on a desktop, it struggles in a mobile setting. Despite my efforts, I have yet to discover a suitable alternative that seamlessly ope ...

Retrieving a variable beyond the scope of jQuery's document.ready() function

I'm feeling quite frustrated and hopeful that someone can assist me with this issue. I don't have strong skills in JavaScript or JQuery (I'm more of a back-end developer), but I've looked everywhere for a solution to no avail. Here is a ...

Transforming text elements into JSON format

My text contains a list of items formatted as follows: var text = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso ...

Generating dynamic div elements using jQuery

I am currently working on developing a button that will automatically generate pre-formatted divs each time it is clicked. The divs consist of forms with fields that should already be populated with data stored in JavaScript variables. Example: <d ...

What is the most efficient method for storing and retrieving numerous DOM elements as JSON using the FileSystem (fs) Module in Node.js?

Is there a way to efficiently save dynamically added DOM elements, such as draggable DIVs, to a file and then reload them later on? I am looking for the most organized approach to achieve this. ...

The class 'ConsoleTVsChartsCharts' could not be located

Attempting to implement Laravel charts using the package consoletvs/charts:6.*, Utilizing service providers ConsoleTVs\Charts\ChartsServiceProvider::class, With an alias: 'Charts' => ConsoleTVs\Charts\Charts::class, ...

Identify all elements that include the designated text within an SVG element

I want to target all elements that have a specific text within an SVG tag. For example, you can use the following code snippet: [...document.querySelectorAll("*")].filter(e => e.childNodes && [...e.childNodes].find(n => n.nodeValue ...

Having trouble with Bootstrap 5 Carousel not sliding to the next image? Learn how to fix this issue by upgrading from Bootstrap 4 to Bootstrap 5

Having downloaded both the compiled css and js and the source files of the bootstrap 5 library, I've experimented with both. While the css seems to load fine, I'm struggling to get this example to function. It's from a bootstrap 4 related po ...

We are experiencing difficulties rendering flash messages in Expressjs with Handlebars(hbs) and express-messages using flash-connect

I'm working on an express app and I want to display flash messages when a user signs up using a form. The technologies I am utilizing include Node.js, Express.js, Handlebars(hbs), connect-flash, and express-messages. To make finding errors easier, I ...