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);
|
||||
|
||||
useEffect(() => {
|
||||
let interval: NodeJS.Timeout | null = null;
|
||||
|
||||
async function fetchRichPresence() {
|
||||
try {
|
||||
const response = await fetch(`https://api.lanyard.rest/v1/users/${userId}`);
|
||||
const json: LanyardResponse = await response.json();
|
||||
if (json.success) {
|
||||
if (json.success)
|
||||
setPresence(json.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch Lanyard presence:", error);
|
||||
} finally {
|
||||
@@ -148,9 +149,39 @@ export function DiscordStatus({ userId }: DiscordStatusParams) {
|
||||
}
|
||||
}
|
||||
|
||||
fetchRichPresence();
|
||||
const interval = setInterval(fetchRichPresence, 30000);
|
||||
return () => clearInterval(interval);
|
||||
const startPolling = () => {
|
||||
if (!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]);
|
||||
|
||||
if (loading)
|
||||
|
||||
Reference in New Issue
Block a user