1- import { useEffect , useRef , useState } from 'react'
1+ import { useEffect , useState } from 'react'
22
33import { noop , useMainContext } from '@devtron-labs/devtron-fe-common-lib'
44
5- import { getInternetConnectivity } from '@Services/service'
6-
7- import { INTERNET_CONNECTIVITY_INTERVAL } from '../constants'
8-
95export const useOnline = ( { onOnline = noop , onOffline = noop } : { onOnline ?: ( ) => void ; onOffline ?: ( ) => void } ) => {
106 const [ online , setOnline ] = useState ( structuredClone ( navigator . onLine ) )
11- const abortControllerRef = useRef < AbortController > ( new AbortController ( ) )
12- const timeoutRef = useRef < NodeJS . Timeout > ( null )
137 const { isAirgapped } = useMainContext ( )
148
15- const checkConnectivity = async ( ) => {
16- if ( isAirgapped ) return
17- // Cancel any pending request
18- if ( abortControllerRef . current ) {
19- abortControllerRef . current . abort ( )
20- }
21-
22- const controller = new AbortController ( )
23- abortControllerRef . current = controller
24-
25- try {
26- await getInternetConnectivity ( abortControllerRef . current )
27- setOnline ( true )
28- if ( online ) {
29- onOnline ( )
30- }
31- } catch {
32- setOnline ( false )
33- } finally {
34- timeoutRef . current = setTimeout ( checkConnectivity , INTERNET_CONNECTIVITY_INTERVAL )
35- }
36- }
379 const handleOffline = ( ) => {
38- if ( timeoutRef . current ) {
39- clearTimeout ( timeoutRef . current )
40- }
41- abortControllerRef . current . abort ( )
4210 setOnline ( false )
4311 if ( onOffline ) {
4412 onOffline ( )
4513 }
4614 }
4715
48- const handleOnline = async ( ) => {
49- // Verify connectivity when browser reports online
50- await checkConnectivity ( )
16+ const handleOnline = ( ) => {
17+ setOnline ( navigator . onLine )
18+ onOnline ( )
5119 }
5220
5321 useEffect ( ( ) => {
@@ -56,12 +24,8 @@ export const useOnline = ({ onOnline = noop, onOffline = noop }: { onOnline?: ()
5624 window . addEventListener ( 'offline' , handleOffline )
5725
5826 return ( ) => {
59- if ( timeoutRef . current ) {
60- clearTimeout ( timeoutRef . current )
61- }
6227 window . removeEventListener ( 'offline' , handleOffline )
6328 window . removeEventListener ( 'online' , handleOnline )
64- abortControllerRef . current . abort ( )
6529 }
6630 } , [ isAirgapped ] )
6731
0 commit comments