fix?: only poll presence if tab is visible
This commit is contained in:
@@ -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) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const startPolling = () => {
|
||||||
|
if (!interval) {
|
||||||
fetchRichPresence();
|
fetchRichPresence();
|
||||||
const interval = setInterval(fetchRichPresence, 30000);
|
interval = setInterval(fetchRichPresence, 30000);
|
||||||
return () => clearInterval(interval);
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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)
|
||||||
|
|||||||
Reference in New Issue
Block a user