Home > database >  hide modal on when disconnected from internet
hide modal on when disconnected from internet

Time:09-15

I have a helper function connected(), this function is testing whether a user is online or not. It returns false if offline. I have this ant design modal and I am trying to call this function in the visible prop, in order to hide the modal if the user is not connected. I am not sure I am doing this right. Is it also necessary to put to have a useEffect ? Any idea on how to achieve this result

export const connected = async () => {
    try {
        const online = await fetch('/connection');
        return online.status >= 200 && online.status < 300
    } catch (err) {
        return false 
    }
}


    <Modal
     title={test}
     centered
     visible={connected() ? isVisible : false}
     closable={true}
     onCancel={closeModal}
     width={400}
    >
    <p>test</p>
    </Modal>

CodePudding user response:

Have a look at navigator.onLine

basic code to check connection status:

if (navigator.onLine) {
  console.log('online');
} else {
  console.log('offline');
}

link to documentation: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine

CodePudding user response:

You did it wrong, and let me explain why.

Your function connected return promise, and when you working with promises your should either wait for the promise to finish, or use the Promise.prototype.then, and Promise.prototype.catch.

Right now your modal will be always visible, becuase connected() return a Promise(), not a valid boolean.

To make it work, you can use one of the following methods:

Method 1: using await

const conntectedValue = await conntected();

Method 2: using Promose.prototype.then() and .catch()

let connectedStatus = false;
connected().then(() => {
    connectedStatus = true;
}).catch(() => {
    connectedStatus = false;
})

Or you can use events to check connectivity.

window.addEventListener('offline', (e) => { console.log('offline'); });

window.addEventListener('online', (e) => { console.log('online'); });

I hope I explained clearly.

  • Related