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?