Skip to content

Commit

Permalink
feat: added a new hook to know the connection status
Browse files Browse the repository at this point in the history
  • Loading branch information
Franqsanz committed May 10, 2024
1 parent 32791c5 commit 8af9698
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 1 deletion.
32 changes: 31 additions & 1 deletion src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,27 @@
import React from 'react';
import { NavLink } from 'react-router-dom';
import { Flex, useColorModeValue, Link } from '@chakra-ui/react';
import { Box, Flex, useColorModeValue, Link } from '@chakra-ui/react';

import { useNetworkState } from '@hooks/useNetworkState';

export function Footer() {
const bgFooter = useColorModeValue('gray.100', 'gray.900');
const networkState = useNetworkState();
let connectionState;

if (networkState === 'online') {
connectionState = (
<Box w='14px' h='14px' rounded='full' bg='green.500'></Box>
);
}

if (networkState === 'offline') {
connectionState = <Box w='14px' h='14px' rounded='full' bg='red'></Box>;
}

if (networkState === 'slow') {
connectionState = <Box w='14px' h='14px' rounded='full' bg='#ffc700'></Box>;
}

return (
<>
Expand All @@ -26,6 +44,18 @@ export function Footer() {
>
Políticas de Privacidad
</Link>
<Flex
mt='3'
align='center'
fontSize='xs'
bg='black'
p='2'
rounded='lg'
color='#EAEAEA'
>
<Box mr='2'>Estado de conexión</Box>
{connectionState}
</Flex>
</Flex>
</>
);
Expand Down
48 changes: 48 additions & 0 deletions src/hooks/useNetworkState.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { useEffect, useState } from 'react';

type NetworkState = 'online' | 'offline' | 'slow';

export function useNetworkState(): NetworkState {
const [networkState, setNetworkState] = useState<NetworkState>('online');

useEffect(() => {
function handleNetworkChange() {
if (navigator.onLine) {
// Comprobar si la velocidad de conexión es lenta o no
const connection =
(navigator as any).connection ||
(navigator as any).mozConnection ||
(navigator as any).webkitConnection;

if (connection) {
const effectiveType = connection.effectiveType;

if (
effectiveType === 'slow-2g' ||
effectiveType === '2g' ||
effectiveType === '3g'
) {
setNetworkState('slow');
} else {
setNetworkState('online');
}
} else {
setNetworkState('online');
}
} else {
setNetworkState('offline');
}
}

window.addEventListener('online', handleNetworkChange);
window.addEventListener('offline', handleNetworkChange);
handleNetworkChange();

return () => {
window.removeEventListener('online', handleNetworkChange);
window.removeEventListener('offline', handleNetworkChange);
};
}, []);

return networkState;
}

0 comments on commit 8af9698

Please sign in to comment.