Skip to content

[URH-58] useOnlineStatus 신규 #47

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions src/hooks/useOnlineStatus.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { act, renderHook } from '@testing-library/react';
import useOnlineStatus from './useOnlineStatus';

let windowSpy: jest.SpyInstance;
let onlineCallback: jest.Mock;
let offlineCallback: jest.Mock;

describe('useOnlineStatus', () => {
beforeEach(() => {
windowSpy = jest.spyOn(global, 'window', 'get');
onlineCallback = jest.fn();
offlineCallback = jest.fn();
});

afterEach(() => {
windowSpy.mockRestore();
});

test('온라인 상태라면 isOnline은 true이다.', () => {
jest.spyOn(navigator, 'onLine', 'get').mockReturnValueOnce(true);

const { result } = renderHook(() => useOnlineStatus());

expect(result.current.isOnline).toBe(true);
});

test('오프라인 상태에서 isOnline은 false이다.', () => {
jest.spyOn(navigator, 'onLine', 'get').mockReturnValueOnce(false);

const { result } = renderHook(() => useOnlineStatus());

expect(result.current.isOnline).toBe(false);
});

test('네트워크 상태가 변경되면 isOnline 상태가 갱신된다.', () => {
const { result } = renderHook(() => useOnlineStatus());

act(() => {
window.dispatchEvent(new Event('offline'));
});

expect(result.current.isOnline).toBe(false);

act(() => {
window.dispatchEvent(new Event('online'));
});

expect(result.current.isOnline).toBe(true);
});

test('콜백 함수가 호출되는지 확인', () => {
renderHook(() => useOnlineStatus({ onlineCallback, offlineCallback }));
act(() => {
window.dispatchEvent(new Event('offline'));
});

expect(offlineCallback).toHaveBeenCalledTimes(1);

act(() => {
window.dispatchEvent(new Event('online'));
});
expect(onlineCallback).toHaveBeenCalledTimes(1);
});

test('언마운트 시 이벤트 리스너가 제거된다.', () => {
const { unmount } = renderHook(() =>
useOnlineStatus({ onlineCallback, offlineCallback })
);

unmount();

act(() => {
window.dispatchEvent(new Event('offline'));
});
expect(offlineCallback).toHaveBeenCalledTimes(0);

act(() => {
window.dispatchEvent(new Event('online'));
});
expect(onlineCallback).toHaveBeenCalledTimes(0);
});
});
68 changes: 68 additions & 0 deletions src/hooks/useOnlineStatus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { useEffect, useState } from 'react';
import { Fn } from '../types';
import { hasNavigator } from '../utils';

interface useOnlineStatusProps {
onlineCallback?: Fn;
offlineCallback?: Fn;
}

interface UseOnlineStatusReturns {
isOnline: boolean;
}

/**
* 온라인/오프라인 네트워크 상태를 판별하는 훅.
*
* @param {Object} props - 훅에 전달되는 옵션 객체
* @param {Fn} [props.onlineCallback] - 브라우저가 온라인 상태가 될 때 실행할 콜백 함수
* @param {Fn} [props.offlineCallback] - 브라우저가 오프라인 상태가 될 때 실행할 콜백 함수
*
* @returns {{ isOnline: boolean }} - 현재 온라인 상태를 나타내는 객체
*
* @description
* 브라우저의 온라인/오프라인 상태를 추적하는 훅입니다.
* 온라인 상태가 변경될 때 실행할 콜백 함수를 선택적으로 지정할 수 있습니다.
* 콜백 함수들은 `useCallback`을 사용하여 메모이제이션 할 것을 권장합니다.
* 이를 통해 의도하지 않은 재생성을 방지하고 성능을 최적화할 수 있습니다.
*/

const useOnlineStatus = ({
onlineCallback = () => {},
offlineCallback = () => {},
}: useOnlineStatusProps = {}): UseOnlineStatusReturns => {
const [isOnline, setIsOnline] = useState(() =>
hasNavigator() ? navigator.onLine : false
);

useEffect(() => {
if (!hasNavigator()) {
console.error('navigator is not supported in this environment.');
return;
}

const handleOnline = () => {
setIsOnline(true);
onlineCallback();
};

const handleOffline = () => {
setIsOnline(false);
offlineCallback();
};

window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);

return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, [onlineCallback, offlineCallback]);

return {
isOnline,
};
};

export default useOnlineStatus;
2 changes: 1 addition & 1 deletion src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { delayExecution, type CancelToken } from './delayExecution';
export { throttle } from './throttle';
export { isClient } from './isClient';
export { isClient, hasNavigator } from './isClient';
export { isTouchDevice } from './isTouchDevice';
4 changes: 4 additions & 0 deletions src/utils/isClient.ts
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
export const isClient = typeof window !== 'undefined';

export const hasNavigator = () => {
return isClient && typeof navigator !== 'undefined';
};