I have created a function that checks if the application is online or not. However, based on the MDN documentation, navigator.onLine is giving false positives on Chrome and Safari which I'm currently experiencing right now. Is there any other way to resolve this current issue?
useOnlineStatus.ts:
import { useEffect, useState } from 'react'
const getOnlineStatus = (): boolean => {
return typeof navigator !== 'undefined' &&
typeof navigator.onLine === 'boolean'
? navigator.onLine
: true
}
const useOnlineStatus = (): boolean => {
const [onlineStatus, setOnlineStatus] = useState(getOnlineStatus())
const goOnline = () => setOnlineStatus(true)
const goOffline = () => setOnlineStatus(false)
useEffect(() => {
window.addEventListener('online', goOnline)
window.addEventListener('offline', goOffline)
return () => {
window.removeEventListener('online', goOnline)
window.removeEventListener('offline', goOffline)
}
}, [])
return onlineStatus
}
export default useOnlineStatus
One way you could try is to send a request to your own origin to check whether your application is online or not.
The query params (q) is randomised to avoid cached responses.