fix?: only poll presence if tab is visible

This commit is contained in:
2026-05-31 11:47:54 -03:00
parent 7791f6a684
commit 105518282f
+36 -5
View File
@@ -134,13 +134,14 @@ export function DiscordStatus({ userId }: DiscordStatusParams) {
const [loading, setLoading] = useState<boolean>(true); const [loading, setLoading] = useState<boolean>(true);
useEffect(() => { useEffect(() => {
let interval: NodeJS.Timeout | null = null;
async function fetchRichPresence() { async function fetchRichPresence() {
try { try {
const response = await fetch(`https://api.lanyard.rest/v1/users/${userId}`); const response = await fetch(`https://api.lanyard.rest/v1/users/${userId}`);
const json: LanyardResponse = await response.json(); const json: LanyardResponse = await response.json();
if (json.success) { if (json.success)
setPresence(json.data); setPresence(json.data);
}
} catch (error) { } catch (error) {
console.error("Failed to fetch Lanyard presence:", error); console.error("Failed to fetch Lanyard presence:", error);
} finally { } finally {
@@ -148,9 +149,39 @@ export function DiscordStatus({ userId }: DiscordStatusParams) {
} }
} }
fetchRichPresence(); const startPolling = () => {
const interval = setInterval(fetchRichPresence, 30000); if (!interval) {
return () => clearInterval(interval); fetchRichPresence();
interval = setInterval(fetchRichPresence, 30000);
}
};
const stopPolling = () => {
if (interval) {
clearInterval(interval);
interval = null;
}
};
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible')
startPolling();
else
stopPolling();
};
if (document.visibilityState === 'visible')
startPolling();
else
setLoading(false);
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
stopPolling();
};
}, [userId]); }, [userId]);
if (loading) if (loading)