Search code examples
firebasereact-nativegoogle-cloud-firestorereact-native-firebase

react-native-firebase see if user has an internet connection


I'm trying to upload something to my firestore database, but if the user doesn't have an internet connection it just tries to upload it foreever withour giving me an error.

Is there a way to cancel it when I don't have a connection?


Solution

  • I see two options:

    1. use react-native-netinfo to detect if there's a connection before uploading, something like
    NetInfo.fetch().then(({isConnected}) => {
      if (isConnected) {
        doSomethingWithFirebase();
      }
    });
    
    1. Add a timeout to make it fail, like so:
    // make it a promise, if it isn't already
    const firebaseResult = new Promise(resolve => {
      doSomethingWithFirebase()
        .then(() => resolve(true))
        .catch(() => resolve(false))
    })
    // resolve after 30s
    const timeout = new Promise(resolve => setTimeout(() => resolve(false), 30 * 1000));
    
    const didUpload = await Promise.race([firebasePromise, timeOut]);
    

    I'd personally go with #2, because you can show the user an error (something like "failed to upload. does your connection work?") but it depends what it's for, like if it's analytics data that you don't want them to know about #1 is good for that.

    Edit: as OP pointed out, with #2 the action would take place when the connection came back online again, without notice, which may not be desired behavior. You could indicate that there's an open connection somehow, like with an "uploading" icon, and clear it when it finally resolves (with failure or success).