react query ftw
This commit is contained in:
@@ -1,67 +1,84 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCurrentAccount } from "./useCurrentAccount";
|
||||
import { proxyFetch } from "@/lib/utils";
|
||||
import { useEffect } from "react";
|
||||
|
||||
type AccountSettings = {
|
||||
ChangeUsernameEnabled: boolean
|
||||
ChangeUsernameEnabled: boolean;
|
||||
|
||||
/* determines if the account owner is a roblox admin */
|
||||
IsAdmin: boolean,
|
||||
IsAdmin: boolean;
|
||||
|
||||
PreviousUserNames: string,
|
||||
PreviousUserNames: string;
|
||||
|
||||
/* censored out email */
|
||||
UserEmail: string,
|
||||
UserEmail: string;
|
||||
|
||||
UserAbove13: boolean,
|
||||
UserAbove13: boolean;
|
||||
|
||||
/* does the user have roblox premium */
|
||||
IsPremium: boolean,
|
||||
IsPremium: boolean;
|
||||
|
||||
/* ingame chat */
|
||||
IsGameChatSettingEnabled: boolean
|
||||
}
|
||||
IsGameChatSettingEnabled: boolean;
|
||||
};
|
||||
|
||||
export function useAccountSettings() {
|
||||
const acct = useCurrentAccount();
|
||||
const [accountSettings, setAccountSettings] = useState<AccountSettings | false | null>(null);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
useEffect(() => {
|
||||
if (!acct) return;
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const fetchSetttings = async () => {
|
||||
if (!acct || cancelled) return;
|
||||
const { data: accountSettings } = useQuery<AccountSettings | false | null>({
|
||||
queryKey: ["account-settings", acct ? acct.id : "acctId"],
|
||||
queryFn: async () => {
|
||||
if (!acct) return null;
|
||||
try {
|
||||
const res = await proxyFetch(
|
||||
`https://www.roblox.com/my/settings/json`
|
||||
);
|
||||
if (!res.ok) {
|
||||
console.error(
|
||||
`[useAccountSettings] API Error ${res.status} ${res.statusText}`
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const data = await res.json();
|
||||
if (!cancelled) setAccountSettings(data);
|
||||
} catch {
|
||||
if (!cancelled) setAccountSettings(false);
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"[useAccountSettings] Failed to fetch settings",
|
||||
error
|
||||
);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
fetchSetttings();
|
||||
},
|
||||
enabled: !!acct,
|
||||
staleTime: Infinity,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnMount: false,
|
||||
refetchOnReconnect: false
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const handleTransaction = () => {
|
||||
fetchSetttings();
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["account-settings", acct ? acct.id : "acctId"]
|
||||
});
|
||||
};
|
||||
|
||||
window.addEventListener("settingTransactionCompletedEvent", handleTransaction);
|
||||
window.addEventListener(
|
||||
"settingTransactionCompletedEvent",
|
||||
handleTransaction
|
||||
);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.removeEventListener(
|
||||
"settingTransactionCompletedEvent",
|
||||
handleTransaction
|
||||
);
|
||||
};
|
||||
}, [acct]);
|
||||
}, [acct ? acct.id : "acctId", queryClient]);
|
||||
|
||||
return accountSettings;
|
||||
}
|
||||
|
||||
@@ -1,63 +1,64 @@
|
||||
// https://avatar.roblox.com/v2/avatar/users/1083030325/outfits?isEditable=true&itemsPerPage=50&outfitType=Avatar
|
||||
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect } from "react";
|
||||
import { useCurrentAccount } from "./useCurrentAccount";
|
||||
import { proxyFetch } from "@/lib/utils";
|
||||
import { loadThumbnails } from "@/lib/thumbnailLoader";
|
||||
|
||||
type Outfit = {
|
||||
name: string,
|
||||
id: number
|
||||
}
|
||||
name: string;
|
||||
id: number;
|
||||
};
|
||||
|
||||
export function useAvatarOutfits() {
|
||||
export function useAvatarOutfits(): Outfit[] | false | null {
|
||||
const acct = useCurrentAccount();
|
||||
const [outfits, setOutfits] = useState<Outfit[] | false | null>(null);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const query = useQuery<Outfit[] | false>({
|
||||
queryKey: ["avatarOutfits", acct ? acct.id : "acctId"],
|
||||
enabled: !!acct,
|
||||
queryFn: async () => {
|
||||
if (!acct) return false;
|
||||
|
||||
const res = await proxyFetch(
|
||||
`https://avatar.roblox.com/v2/avatar/users/${acct.id}/outfits?page=1&itemsPerPage=25&isEditable=true`
|
||||
);
|
||||
const data = (await res.json()) as { data: Outfit[] };
|
||||
|
||||
loadThumbnails(
|
||||
data.data.map((a) => ({
|
||||
type: "Outfit",
|
||||
targetId: a.id,
|
||||
format: "webp",
|
||||
size: "420x420"
|
||||
}))
|
||||
).catch(() => {});
|
||||
|
||||
return data.data;
|
||||
},
|
||||
staleTime: 1000 * 60 * 5,
|
||||
refetchOnWindowFocus: false
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!acct) return;
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const fetchSetttings = async () => {
|
||||
if (!acct || cancelled) return;
|
||||
try {
|
||||
const res = await proxyFetch(
|
||||
`https://avatar.roblox.com/v2/avatar/users/${acct.id}/outfits?page=1&itemsPerPage=25&isEditable=true`
|
||||
);
|
||||
const data = await res.json() as {data: Outfit[]};
|
||||
if (!cancelled) {
|
||||
setOutfits(data.data);
|
||||
loadThumbnails(data.data.map(a=>({
|
||||
type: "Outfit",
|
||||
targetId: a.id,
|
||||
format: "webp",
|
||||
size: "420x420"
|
||||
}))).catch(a=>{})
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) setOutfits(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchSetttings();
|
||||
|
||||
const handleTransaction = () => {
|
||||
fetchSetttings();
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["avatarOutfits", acct ? acct.id : "acctId"]
|
||||
});
|
||||
};
|
||||
|
||||
window.addEventListener("avatarTransactionCompletedEvent", handleTransaction);
|
||||
|
||||
window.addEventListener(
|
||||
"avatarTransactionCompletedEvent",
|
||||
handleTransaction
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.removeEventListener(
|
||||
"avatarTransactionCompletedEvent",
|
||||
handleTransaction
|
||||
);
|
||||
};
|
||||
}, [acct]);
|
||||
}, [acct ? acct.id : "acctId", queryClient]);
|
||||
|
||||
return outfits;
|
||||
return query.data ?? null;
|
||||
}
|
||||
|
||||
@@ -1,46 +1,41 @@
|
||||
"use client";
|
||||
|
||||
// https://friends.roblox.com/v1/users/1083030325/friends/find?userSort=1
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useCurrentAccount } from "./useCurrentAccount";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { proxyFetch } from "@/lib/utils";
|
||||
import { loadThumbnails } from "@/lib/thumbnailLoader";
|
||||
import { useCurrentAccount } from "./useCurrentAccount";
|
||||
|
||||
let isFetching = false;
|
||||
let cachedData: any = null;
|
||||
|
||||
export function useBestFriends() {
|
||||
export function useBestFriends():
|
||||
| {
|
||||
hasVerifiedBadge: boolean;
|
||||
id: number;
|
||||
name: string;
|
||||
displayName: string;
|
||||
}[]
|
||||
| null
|
||||
| false {
|
||||
const acct = useCurrentAccount();
|
||||
const [friends, setFriends] = useState<
|
||||
|
||||
const query = useQuery<
|
||||
| {
|
||||
hasVerifiedBadge: boolean;
|
||||
id: number;
|
||||
name: string;
|
||||
displayName: string;
|
||||
}[]
|
||||
| null
|
||||
| false
|
||||
>(cachedData);
|
||||
>({
|
||||
queryKey: ["bestFriends", acct ? acct.id : "acctId"],
|
||||
enabled: !!acct,
|
||||
queryFn: async () => {
|
||||
if (!acct) return false;
|
||||
|
||||
const BestFriendIDs = JSON.parse(
|
||||
window.localStorage.getItem("BestFriendsStore") || "[]"
|
||||
) as number[];
|
||||
|
||||
if (BestFriendIDs.length === 0) return [];
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
if (!acct) return;
|
||||
if (isFetching) {
|
||||
const IN = setInterval(() => {
|
||||
if (cachedData !== null) {
|
||||
if (!cancelled) setFriends(cachedData);
|
||||
clearInterval(IN);
|
||||
}
|
||||
}, 50);
|
||||
return () => {
|
||||
clearInterval(IN);
|
||||
cancelled = true;
|
||||
};
|
||||
}
|
||||
isFetching = true;
|
||||
(async () => {
|
||||
const BestFriendIDs = JSON.parse(window.localStorage.getItem("BestFriendsStore") || "[]") as number[]
|
||||
const friendsAPICall2 = await proxyFetch(
|
||||
`https://users.roblox.com/v1/users`,
|
||||
{
|
||||
@@ -51,6 +46,7 @@ export function useBestFriends() {
|
||||
})
|
||||
}
|
||||
);
|
||||
|
||||
const J2 = (await friendsAPICall2.json()) as {
|
||||
data: {
|
||||
hasVerifiedBadge: boolean;
|
||||
@@ -59,6 +55,7 @@ export function useBestFriends() {
|
||||
displayName: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
loadThumbnails(
|
||||
J2.data.map((a) => ({
|
||||
type: "AvatarHeadShot",
|
||||
@@ -67,7 +64,8 @@ export function useBestFriends() {
|
||||
format: "webp"
|
||||
}))
|
||||
).catch(() => {});
|
||||
const friendsList = BestFriendIDs.map((a) => {
|
||||
|
||||
return BestFriendIDs.map((a) => {
|
||||
const x = J2.data.find((b) => b.id === a);
|
||||
return {
|
||||
id: a,
|
||||
@@ -76,14 +74,10 @@ export function useBestFriends() {
|
||||
displayName: x?.displayName || "?"
|
||||
};
|
||||
});
|
||||
if (!cancelled) setFriends(friendsList);
|
||||
cachedData = friendsList;
|
||||
isFetching = false;
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [acct]);
|
||||
},
|
||||
staleTime: 1000 * 60 * 5,
|
||||
refetchOnWindowFocus: false
|
||||
});
|
||||
|
||||
return friends;
|
||||
return query.data ?? null;
|
||||
}
|
||||
|
||||
@@ -1,61 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
getLoggedInUser,
|
||||
getUserByUserId,
|
||||
UserProfileDetails
|
||||
} from "@/lib/profile";
|
||||
import { loadThumbnails } from "@/lib/thumbnailLoader";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
let isFetching = false;
|
||||
let cachedData: UserProfileDetails | null | false = null;
|
||||
|
||||
export function useCurrentAccount() {
|
||||
const [profileDetails, setProfileDetails] = useState<
|
||||
UserProfileDetails | null | false
|
||||
>(cachedData);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
if (profileDetails !== null && profileDetails !== undefined) return;
|
||||
if (isFetching) {
|
||||
const IN = setInterval(() => {
|
||||
if (cachedData !== null) {
|
||||
if (!cancelled) setProfileDetails(cachedData);
|
||||
clearInterval(IN);
|
||||
}
|
||||
}, 50);
|
||||
return () => {
|
||||
clearInterval(IN);
|
||||
cancelled = true;
|
||||
};
|
||||
}
|
||||
isFetching = true;
|
||||
(async () => {
|
||||
export function useCurrentAccount(): UserProfileDetails | null | false {
|
||||
const query = useQuery<UserProfileDetails | false>({
|
||||
queryKey: ["currentAccount"],
|
||||
queryFn: async () => {
|
||||
const authed = await getLoggedInUser();
|
||||
if (authed) {
|
||||
const user = await getUserByUserId(authed.id.toString());
|
||||
if (!cancelled) setProfileDetails(user);
|
||||
cachedData = user;
|
||||
loadThumbnails([
|
||||
{
|
||||
type: "AvatarHeadShot",
|
||||
targetId: authed.id,
|
||||
format: "webp",
|
||||
size: "720x720"
|
||||
}
|
||||
]).catch(() => {});
|
||||
} else {
|
||||
if (!cancelled) setProfileDetails(false);
|
||||
cachedData = false;
|
||||
}
|
||||
isFetching = false;
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [profileDetails]);
|
||||
if (!authed) return false;
|
||||
|
||||
return profileDetails;
|
||||
const user = await getUserByUserId(authed.id.toString());
|
||||
|
||||
loadThumbnails([
|
||||
{
|
||||
type: "AvatarHeadShot",
|
||||
targetId: authed.id,
|
||||
format: "webp",
|
||||
size: "720x720"
|
||||
}
|
||||
]).catch(() => {});
|
||||
|
||||
return user;
|
||||
},
|
||||
staleTime: 1000 * 60 * 5,
|
||||
refetchOnWindowFocus: false
|
||||
});
|
||||
|
||||
return query.data ?? null;
|
||||
}
|
||||
|
||||
@@ -1,64 +1,34 @@
|
||||
"use client";
|
||||
|
||||
// https://friends.roblox.com/v1/users/1083030325/friends/find?userSort=1
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useCurrentAccount } from "./useCurrentAccount";
|
||||
import { proxyFetch } from "@/lib/utils";
|
||||
import { loadThumbnails } from "@/lib/thumbnailLoader";
|
||||
|
||||
let isFetching = false;
|
||||
let cachedData: any = null;
|
||||
import { UserProfileDetails } from "@/lib/profile";
|
||||
|
||||
export function useFriendsHome() {
|
||||
const acct = useCurrentAccount();
|
||||
const [friends, setFriends] = useState<
|
||||
| {
|
||||
hasVerifiedBadge: boolean;
|
||||
id: number;
|
||||
name: string;
|
||||
displayName: string;
|
||||
}[]
|
||||
| null
|
||||
| false
|
||||
>(cachedData);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
if (!acct) return;
|
||||
if (isFetching) {
|
||||
const IN = setInterval(() => {
|
||||
if (cachedData !== null) {
|
||||
if (!cancelled) setFriends(cachedData);
|
||||
clearInterval(IN);
|
||||
}
|
||||
}, 50);
|
||||
return () => {
|
||||
clearInterval(IN);
|
||||
cancelled = true;
|
||||
};
|
||||
}
|
||||
isFetching = true;
|
||||
(async () => {
|
||||
const { data: friends } = useQuery({
|
||||
queryKey: ["friends", acct ? acct.id : "acctId"],
|
||||
queryFn: async () => {
|
||||
if (!acct) return null;
|
||||
const friendsAPICall = await proxyFetch(
|
||||
`https://friends.roblox.com/v1/users/${acct.id}/friends` // /find?userSort=1
|
||||
`https://friends.roblox.com/v1/users/${acct.id}/friends`
|
||||
);
|
||||
const J = (await friendsAPICall.json()) as {
|
||||
const j = (await friendsAPICall.json()) as {
|
||||
data: { id: number }[];
|
||||
// PageItems: { id: number }[]; // /find
|
||||
};
|
||||
const friendsAPICall2 = await proxyFetch(
|
||||
`https://users.roblox.com/v1/users`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
userIds: J.data.map((a) => a.id),
|
||||
// userIds: J.PageItems.map((a) => a.id),
|
||||
userIds: j.data.map((a) => a.id),
|
||||
excludeBannedUsers: false
|
||||
})
|
||||
}
|
||||
);
|
||||
const J2 = (await friendsAPICall2.json()) as {
|
||||
const j2 = (await friendsAPICall2.json()) as {
|
||||
data: {
|
||||
hasVerifiedBadge: boolean;
|
||||
id: number;
|
||||
@@ -67,15 +37,15 @@ export function useFriendsHome() {
|
||||
}[];
|
||||
};
|
||||
loadThumbnails(
|
||||
J2.data.map((a) => ({
|
||||
j2.data.map((a) => ({
|
||||
type: "AvatarHeadShot",
|
||||
size: "420x420",
|
||||
targetId: a.id,
|
||||
format: "webp"
|
||||
}))
|
||||
).catch(() => {});
|
||||
const friendsList = J.data.map((a) => { // J.PageItems /find
|
||||
const x = J2.data.find((b) => b.id === a.id);
|
||||
const friendsList = j.data.map((a) => {
|
||||
const x = j2.data.find((b) => b.id === a.id);
|
||||
return {
|
||||
id: a.id,
|
||||
hasVerifiedBadge: x?.hasVerifiedBadge || false,
|
||||
@@ -83,14 +53,14 @@ export function useFriendsHome() {
|
||||
displayName: x?.displayName || "?"
|
||||
};
|
||||
});
|
||||
if (!cancelled) setFriends(friendsList);
|
||||
cachedData = friendsList;
|
||||
isFetching = false;
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [acct]);
|
||||
return friendsList;
|
||||
},
|
||||
enabled: !!acct,
|
||||
staleTime: 300000, // 5 minutes
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnMount: false,
|
||||
refetchOnReconnect: false
|
||||
});
|
||||
|
||||
return friends;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
"use client";
|
||||
|
||||
// smartass method by google gemini
|
||||
|
||||
import { useEffect, useState, useMemo } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useCurrentAccount } from "./useCurrentAccount";
|
||||
import { proxyFetch } from "@/lib/utils";
|
||||
|
||||
@@ -16,114 +14,53 @@ type PresenceData = {
|
||||
userId: number;
|
||||
};
|
||||
|
||||
// --- Internal Shared State ---
|
||||
|
||||
/**
|
||||
* A Map to track subscribers.
|
||||
* Key: The component's update callback function.
|
||||
* Value: The array of user IDs that component is interested in.
|
||||
* This allows multiple components to subscribe with their own lists of IDs.
|
||||
*/
|
||||
let subscribers = new Map<(data: PresenceData[]) => void, number[]>();
|
||||
|
||||
let interval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
let latestData: PresenceData[] = [];
|
||||
|
||||
/**
|
||||
* Fetches presence for all unique user IDs requested by all subscribed components.
|
||||
* @param acctId - The ID of the currently logged-in user.
|
||||
*/
|
||||
async function fetchPresence(acctId: number) {
|
||||
const allIdArrays = [...subscribers.values()];
|
||||
const uniqueUserIds = [...new Set(allIdArrays.flat())];
|
||||
|
||||
if (!acctId || uniqueUserIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await proxyFetch(
|
||||
"https://presence.roblox.com/v1/presence/users",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
userIds: [...new Set([acctId, ...uniqueUserIds])]
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
console.log(`[usePresence] API Error ${res.status} ${res.statusText}`)
|
||||
return
|
||||
// throw new Error(`API request failed with status ${res.status}`);
|
||||
}
|
||||
|
||||
const json = await res.json();
|
||||
latestData = json.userPresences || [];
|
||||
|
||||
subscribers.forEach((_requestedIds, callback) => callback(latestData));
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch presence:", error);
|
||||
latestData = [];
|
||||
subscribers.forEach((_requestedIds, callback) => callback([]));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A React hook to get the real-time presence of a list of Roblox users.
|
||||
* This hook can be used by multiple components simultaneously without conflict.
|
||||
* This hook uses @tanstack/react-query to handle caching and periodic refetching.
|
||||
*
|
||||
* @param userIds - An array of user IDs to track.
|
||||
* @returns An array of PresenceData objects for the requested user IDs.
|
||||
*/
|
||||
export function useFriendsPresence(userIds: number[]) {
|
||||
const acct = useCurrentAccount();
|
||||
const [data, setData] = useState<PresenceData[]>([]);
|
||||
|
||||
const userIdsKey = useMemo(
|
||||
() => JSON.stringify([...userIds].sort()),
|
||||
[userIds]
|
||||
);
|
||||
// Sort userIds to ensure the query key is stable, regardless of the order of IDs.
|
||||
const sortedUserIds = [...(userIds || [])].sort();
|
||||
|
||||
useEffect(() => {
|
||||
if (!acct || !userIds || userIds.length === 0) {
|
||||
setData([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const updateCallback = (globalData: PresenceData[]) => {
|
||||
const filteredData = globalData.filter((presence) =>
|
||||
userIds.includes(presence.userId)
|
||||
);
|
||||
setData(filteredData);
|
||||
};
|
||||
|
||||
updateCallback(latestData);
|
||||
|
||||
subscribers.set(updateCallback, userIds);
|
||||
|
||||
if (!interval) {
|
||||
fetchPresence(acct.id);
|
||||
interval = setInterval(() => fetchPresence(acct.id), 5000);
|
||||
} else {
|
||||
fetchPresence(acct.id);
|
||||
}
|
||||
|
||||
// The cleanup function runs when the component unmounts.
|
||||
return () => {
|
||||
subscribers.delete(updateCallback);
|
||||
|
||||
if (subscribers.size === 0 && interval) {
|
||||
clearInterval(interval);
|
||||
interval = null;
|
||||
latestData = [];
|
||||
const { data: presences = [] } = useQuery({
|
||||
queryKey: ["presence", ...sortedUserIds],
|
||||
queryFn: async () => {
|
||||
if (!acct || sortedUserIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
}, [acct, userIdsKey]);
|
||||
|
||||
return data;
|
||||
const res = await proxyFetch(
|
||||
"https://presence.roblox.com/v1/presence/users",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
userIds: sortedUserIds
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
console.error(
|
||||
`[usePresence] API Error ${res.status} ${res.statusText}`
|
||||
);
|
||||
throw new Error(`API request failed with status ${res.status}`);
|
||||
}
|
||||
|
||||
const json = await res.json();
|
||||
return (json.userPresences || []) as PresenceData[];
|
||||
},
|
||||
enabled: !!acct && sortedUserIds.length > 0,
|
||||
refetchInterval: 5000,
|
||||
refetchOnWindowFocus: false
|
||||
});
|
||||
|
||||
return presences;
|
||||
}
|
||||
|
||||
@@ -1,49 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCurrentAccount } from "./useCurrentAccount";
|
||||
import { proxyFetch } from "@/lib/utils";
|
||||
import { useEffect } from "react";
|
||||
|
||||
export function useRobuxBalance() {
|
||||
const acct = useCurrentAccount();
|
||||
const [robux, setRobux] = useState<number | false | null>(null);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
useEffect(() => {
|
||||
if (!acct) return;
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const fetchBalance = async () => {
|
||||
if (!acct || cancelled) return;
|
||||
const { data: robux } = useQuery<number | false | null>({
|
||||
queryKey: ["robux-balance", acct ? acct.id : "acctId"],
|
||||
queryFn: async () => {
|
||||
if (!acct) return null;
|
||||
try {
|
||||
const res = await proxyFetch(
|
||||
`https://economy.roblox.com/v1/users/${acct.id}/currency`
|
||||
);
|
||||
const data = await res.json();
|
||||
if (!cancelled) setRobux(data.robux);
|
||||
return data.robux;
|
||||
} catch {
|
||||
if (!cancelled) setRobux(false);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
fetchBalance();
|
||||
const interval = setInterval(fetchBalance, 10000);
|
||||
},
|
||||
enabled: !!acct,
|
||||
refetchInterval: 10000,
|
||||
staleTime: 10000
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const handleTransaction = () => {
|
||||
fetchBalance();
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["robux-balance", acct ? acct.id : "acctId"]
|
||||
});
|
||||
};
|
||||
|
||||
window.addEventListener("transactionCompletedEvent", handleTransaction);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearInterval(interval);
|
||||
window.removeEventListener(
|
||||
"transactionCompletedEvent",
|
||||
handleTransaction
|
||||
);
|
||||
};
|
||||
}, [acct]);
|
||||
}, [acct ? acct.id : "acctId", queryClient]);
|
||||
|
||||
return robux;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user