Initial commit
This commit is contained in:
60
hooks/useRealTimeUpdates.ts
Normal file
60
hooks/useRealTimeUpdates.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, useRef } from "react"
|
||||
|
||||
interface UpdateData {
|
||||
stats?: any
|
||||
users?: any[]
|
||||
lastReset?: any
|
||||
}
|
||||
|
||||
export function useRealTimeUpdates(onUpdate?: (data: UpdateData) => void) {
|
||||
const [isConnected, setIsConnected] = useState(false)
|
||||
const intervalRef = useRef<NodeJS.Timeout>()
|
||||
const lastDataRef = useRef<string>("")
|
||||
|
||||
const fetchUpdates = async () => {
|
||||
try {
|
||||
// Fetch all data in parallel
|
||||
const [statsRes, usersRes, resetRes] = await Promise.all([
|
||||
fetch("/api/admin/stats"),
|
||||
fetch("/api/admin/users"),
|
||||
fetch("/api/admin/last-reset"),
|
||||
])
|
||||
|
||||
const [stats, users, lastReset] = await Promise.all([statsRes.json(), usersRes.json(), resetRes.json()])
|
||||
|
||||
const newData = { stats, users, lastReset }
|
||||
const newDataString = JSON.stringify(newData)
|
||||
|
||||
// Only trigger update if data actually changed
|
||||
if (newDataString !== lastDataRef.current) {
|
||||
lastDataRef.current = newDataString
|
||||
if (onUpdate) {
|
||||
onUpdate(newData)
|
||||
}
|
||||
}
|
||||
|
||||
setIsConnected(true)
|
||||
} catch (err) {
|
||||
console.error("Error fetching updates:", err)
|
||||
setIsConnected(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// Initial fetch
|
||||
fetchUpdates()
|
||||
|
||||
// Set up polling every 2 seconds
|
||||
intervalRef.current = setInterval(fetchUpdates, 2000)
|
||||
|
||||
return () => {
|
||||
if (intervalRef.current) {
|
||||
clearInterval(intervalRef.current)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
return { isConnected, refetch: fetchUpdates }
|
||||
}
|
||||
Reference in New Issue
Block a user