LocChat/client/utils/use_jwt_refresh.js

20 lines
597 B
JavaScript
Raw Normal View History

2021-11-23 16:04:12 -05:00
import { useEffect, useRef } from 'react';
export const useJwtRefresh = (authToken, setAuthToken) => {
const refreshTimer = useRef(null);
useEffect(() => {
clearTimeout(refreshTimer.current);
if (authToken) {
refreshTimer.current = setTimeout(async () => {
const result = await fetch('/refresh_token').then((res) => res.json());
if (result.token) {
setAuthToken(result.token);
} else {
setAuthToken(null);
}
}, 60000 * 0.5); // 10 minutes
2021-11-23 16:04:12 -05:00
}
return () => clearTimeout(refreshTimer.current);
}, [authToken]);
};