UNPKG

react-native-inactivity-timeout

Version:

A reusable React Native hook to detect user inactivity and auto logout

61 lines (51 loc) 1.58 kB
// src/useInactivityTimeout.ts import { useEffect, useRef, useCallback } from 'react'; import { Alert, PanResponder, PanResponderInstance } from 'react-native'; interface UseInactivityTimeoutProps { onLogout: () => void; checkExpiration?: () => Promise<boolean>; // Optional token check timeoutDuration?: number; alertMessage?: string; } export const useInactivityTimeout = ({ onLogout, checkExpiration, timeoutDuration = 1000 * 60 * 5, // 5 minutes alertMessage = 'Session expired', }: UseInactivityTimeoutProps) => { const timerId = useRef<NodeJS.Timeout | null>(null); const logout = () => { onLogout(); Alert.alert(alertMessage); }; const resetInactivityTimeout = useCallback(async () => { if (timerId.current) { if (checkExpiration) { const hasTokenExpired = await checkExpiration(); if (hasTokenExpired) { logout(); return; } } clearTimeout(timerId.current); } timerId.current = setTimeout(logout, timeoutDuration); }, [checkExpiration, timeoutDuration, onLogout]); useEffect(() => { resetInactivityTimeout(); return () => { if (timerId.current) { clearTimeout(timerId.current); } }; }, [resetInactivityTimeout]); const panResponder = useRef<PanResponderInstance>( PanResponder.create({ onStartShouldSetPanResponderCapture: () => { resetInactivityTimeout(); return false; }, }) ).current; return { panResponder }; };