Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if server is reachable in react-native

I want to check if the server my app is trying reach is reachable (When internet is reachable) before making a request.

I am using Fetch API and right now I am using function timeout which works well but my question is is there any way by which I can check if server is reachable.

I tried using all-reacheable npm package and added following code but I do not get any call back response.

isReachable([
    'http://aposddasd.com',
    'http://google.com'
], (err, reachable, host) => {
  console.log('Server is' + reachable); //=> false
  console.log('App log' +  host); //=> 'http://aposddasd.com'
});

Can you help me with what is best way to achieve this?

like image 646
Bhumit Mehta Avatar asked Dec 19 '22 10:12

Bhumit Mehta


1 Answers

You can use a Promise.race() which will return the first promise to resolve or reject - they're pretty awesome actually! Checkout the docs here:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/race

Here's a simple function which times out after 3ms - it's using httpbin to simulate a delay of 5s:

const isAvailable = () => {
    const timeout = new Promise((resolve, reject) => {
        setTimeout(reject, 300, 'Request timed out');
    });

    const request = fetch('https://httpbin.org/delay/5');

    return Promise
        .race([timeout, request])
        .then(response => alert('It worked :)'))
        .catch(error => alert('It timed out :('));
}

isAvailable();

Checkout the fiddle here: https://jsfiddle.net/edcs/8Lcg8a8j/10/

like image 97
edcs Avatar answered Jan 09 '23 09:01

edcs