femto-webapp/src/useRefreshSessionLoop.ts
2025-05-20 23:43:43 +02:00

29 lines
759 B
TypeScript

import { useEffect } from 'react'
import { useUser } from './app/user/user.ts'
import { AuthService } from './app/auth/authService.ts'
// Starts a loop that pings the server to keep the session alive, while also getting any updates on the user profile
export function useRefreshSessionLoop(authService: AuthService) {
const user = useUser()
const userId = user?.id ?? null
useEffect(() => {
if (userId == null) {
return
}
const timeouts: Timeout[] = []
timeouts.push(
setTimeout(async function refreshUser() {
await authService.refreshUser(userId)
timeouts.push(setTimeout(refreshUser, 60_000))
}),
)
return () => {
timeouts.forEach(clearTimeout)
}
}, [authService, userId])
}