From 00a1bee73e8cbc917568339b2a20ff80a784ec35 Mon Sep 17 00:00:00 2001 From: Alois Date: Sun, 5 Apr 2026 20:48:35 +0200 Subject: [PATCH] Updated user data caching --- packages/user/src/context.tsx | 51 ++++++++++++++++++++++++++--------- packages/user/src/wrapper.tsx | 2 +- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/packages/user/src/context.tsx b/packages/user/src/context.tsx index 2f05106..72c3446 100644 --- a/packages/user/src/context.tsx +++ b/packages/user/src/context.tsx @@ -19,6 +19,9 @@ const UserContext = React.createContext(undefined); */ export default function UserProvider(props: { children: React.ReactNode }) { const storageRef = React.useRef>({}); + const pendingRef = React.useRef | undefined>>( + {}, + ); const { send } = useTTP(); @@ -27,21 +30,45 @@ export default function UserProvider(props: { children: React.ReactNode }) { * @param userId Parameter userId. * @returns Promise. */ - async function get(userId: number): Promise { - if (storageRef.current[userId] === undefined) { - const userData = await send("get_user_data", { user_id: userId }); + const get = React.useCallback( + async (userId: number): Promise => { + if (userId == null) { + throw new Error("userId is required"); + } - // Temp, add base64 stuff - userData.data.avatar = userData.data.avatar - ? `data:image/png;base64,${userData.data.avatar}` - : undefined; - // Temp end + const cachedUser = storageRef.current[userId]; + if (cachedUser !== undefined) { + return cachedUser; + } - storageRef.current[userId] = userData.data; - } + const pendingUser = pendingRef.current[userId]; + if (pendingUser !== undefined) { + return pendingUser; + } - return storageRef.current[userId]; - } + const request = (async () => { + const userData = await send("get_user_data", { user_id: userId }); + const user = { + ...userData.data, + avatar: userData.data.avatar + ? `data:image/png;base64,${userData.data.avatar}` + : undefined, + }; + + storageRef.current[userId] = user; + return user; + })(); + + pendingRef.current[userId] = request; + + try { + return await request; + } finally { + delete pendingRef.current[userId]; + } + }, + [send], + ); return ( diff --git a/packages/user/src/wrapper.tsx b/packages/user/src/wrapper.tsx index 7533830..bc6da32 100644 --- a/packages/user/src/wrapper.tsx +++ b/packages/user/src/wrapper.tsx @@ -13,7 +13,7 @@ export default function Wrapper(props: { const [user, setUser] = useState(null); useEffect(() => { - if (!props.userId) { + if (props.userId == null) { setUser(failedUser); return; }