Fetch Timeout Issue in React Native

I am currently using fetch to retrieve data from a server. Unfortunately, I am facing issues with setting a timeout for the fetch request in case the server does not respond.

This is my global fetchData class:

fetchGetResp(url, token) {
    return fetch(url, {
        method: "GET",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }
    })
    // .then(ApiUtils.checkStatus)
    .then(response =>
        response.json()
    )
    .then(responseJson => {
        return responseJson
    })
    .catch(error => {
        // console.log(error.headers._bodyText.status);
        console.log('touching undefined catch');
        return undefined;
    });
}

Here is the Javascript class where I am utilizing the fetchData function:

let resp = fetchData.fetchGetResp(restUrl, userToken);
resp.then(responseJson => {
    // console.log(res);
    if (responseJson !== '' && responseJson !== undefined) {

    }
    else {
        console.log(responseJson);
        try {
        }
        catch (error) {
            alert(error.message);
            console.log(error + 'from js file');
        }
    }

    // Some if statement
    else {
        alert('Unable to Process.please try again');
    }
})
.catch(error => {
    alert(error.message + "Please try again after sometime");
});

Please provide guidance on how to implement a timeout feature based on my current approach detailed above.

Answer №1

As of the date 29/12/2017, Fetch does not currently support a timeout option, but discussions are ongoing about implementing it. Check out the discussion link for more information.

If you need to set a timeout for your fetch requests, there is a workaround suggested in these documents: link1, link2

In order to implement a timeout in your case, you can create a custom wrapper function like this:

function timeout(ms, promise) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            reject(new Error("timeout"))
        }, ms);
        promise.then(resolve, reject)
    })
};

timeout(1000, fetchData.fetchGetResp(restUrl, userToken)).then(responseJson => {
    // Your code logic here
}).catch(error => {
    alert(error.message + "Please try again after sometime");
});

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

Is it possible to modify a portion of the zod schema object according to the value of a

My form consists of several fields and a switch component that toggles the visibility of certain parts of the form, as shown below: <Field name="field1" value={value1} /> <Field name="field2" value={value2} /> &l ...

Changing the text color and background color of a span element when a ng-click event is triggered

There are two buttons, Today and Tomorrow, each with an ng-click function. By default, the button background color is white and text color is red. When the Today button is clicked, the background color changes to blue and the text color changes to white. ...

Is it possible to display one division on top of another with a transparent opacity effect in HTML?

I'm struggling with designing web pages and currently working on a page on codepen.io using code from this link. <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1 ...

Complete Form Validation Issue Unresolved by Jquery Validation Plugin

I'm facing an issue with the jQuery validation plugin while attempting to validate a form. Strangely, it only works for one input field. Can anyone suggest a solution? <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.valid ...

Unable to designate the drop-down option as the default selection

Can anyone help me with setting a default drop-down value using JavaScript? I have been struggling to achieve this. You can find my code on jsFiddle <div ng-controller="csrClrt"> <div ng:repeat="(key, item) in items track by $index"> ...

Step-by-step guide to selecting a specific point on an HTML5 canvas using Python's selenium webdriver

Looking to automate interactions with a simple HTML5 application on a website using Selenium webdriver in Python with Firefox on Linux. The challenge is clicking a button on an HTML5 canvas, then dragging one or two objects around the canvas post-button cl ...

What steps are necessary to integrate expo-auth-session with Firebase?

I am working on implementing a feature in my code that will allow users to login and authenticate using their Google credentials. Once they successfully log in, I want them to be added to my authentication database in Firebase. My attempt to achieve this ...

Having trouble parsing an XML received from AJAX request

I am encountering an issue with the code below: $.ajax({ type: "POST", dataType: "xml", url: getUrl('/GetPeriodicStats/'), data: XML.innerHTML,//some xml, success: function(c) { After receiving the XML data in the clie ...

Unable to send headers to the client in expressjs as they have already been set

After successfully logging in, I am trying to redirect to another page but keep encountering the error message "Cannot set headers after they are sent to the client". I understand that I need to place the res.redirect method somewhere else in my code, bu ...

Performing an AJAX call in Rails 4 to update a particular value

I have a voting button on my website that displays the number of votes and adds an extra vote when clicked. I want to implement Ajax so that the page doesn't need to refresh every time a user votes. However, I am new to using Ajax with Rails and not s ...

The webpage is unreachable on localhost after attempting to write to a file using node.js

I'm currently attempting to update a file using Node.js. I have a form that contains checkboxes, and upon form submission, the server should update the file based on which checkboxes are selected: a, b, or c. The JSON file structure is as follows: { ...

What is the best method to display a tooltip for a disabled radio button within a set of radio buttons?

Is there a way to disable a specific radio button based on a condition and display a tooltip only for that disabled button? https://i.stack.imgur.com/niZK1.png import {Tooltip} from '@mui/material'; <Tooltip titl ...

Enabling Cross-Origin Resource Sharing (CORS) with Javascript on the client side during

Currently, I am attempting to incorporate another website's login verification system into my own site. Although the code below is successfully retrieving the correct response ID, I am encountering CORS errors preventing the completion of the login pr ...

Is there a way to concatenate arrays without using the Array.flat method?

I am encountering an issue with a specific function that I have const flat = function(arr, n) { if (n == 0) { return arr; } else if (n == 1) { let newarr = [] for (let i = 0; i < arr.length; i++) { if (Number.isInteger(arr[i])) ...

Having trouble accessing cookies in JavaScript on Internet Explorer 11?

I am facing an issue with my Angular application where cookies are not being read properly in Internet Explorer 11. The JavaScript code works fine on Chrome, but IE seems to be having trouble accessing the cookie data even though it is visible in the devel ...

Retrieve key-value pairs from a database and store them as variables in PHP before transferring them into an array in JavaScript

My challenge lies in loading Chinese characters as keys and their English translations as values from a database into a PHP array, so that I can use them on the client side in JavaScript. The process involves fetching key:value pairs from PHP into a JavaSc ...

Rule for jQuery validation based on variables

I am facing an issue with validation of login asynchronously in my HTML form using the jQuery Validation Plugin. I would like to trigger a request for login validity on blur, and validate it upon receiving a response. Below is the code snippet: var login ...

Ways to execute additional grunt tasks from a registered plugin

I am currently in the process of developing a custom Grunt plugin to streamline a frequently used build process. Normally, I find myself copying and pasting my GruntFile across different projects, but I believe creating a plugin would be more efficient. Th ...

How to export HTML table information to Excel using JQuery and display a Save As dialog box

This script has been an absolute lifesaver for my web application. Huge thanks to sampopes for providing the solution on this specific thread. function exportToExcel() { var tab_text="<table border='2px'><tr bgcolor='#87AFC6& ...

Ways to prevent the execution of JavaScript code?

I have a website that contains a block where AJAX-loaded code is coming from a remote server. How can I prevent potentially harmful code from executing, especially when it originates from a remote source? Is using the "noscript" tag sufficient to protect a ...