diff --git a/src/client/Cosmetics.ts b/src/client/Cosmetics.ts index 821d8e25e..d1f00e88d 100644 --- a/src/client/Cosmetics.ts +++ b/src/client/Cosmetics.ts @@ -29,23 +29,30 @@ export async function handlePurchase( window.location.href = url; } +let __cosmetics: Promise | null = null; export async function fetchCosmetics(): Promise { - try { - const response = await fetch(`${getApiBase()}/cosmetics.json`); - if (!response.ok) { - console.error(`HTTP error! status: ${response.status}`); - return null; - } - const result = CosmeticsSchema.safeParse(await response.json()); - if (!result.success) { - console.error(`Invalid cosmetics: ${result.error.message}`); - return null; - } - return result.data; - } catch (error) { - console.error("Error getting cosmetics:", error); - return null; + if (__cosmetics !== null) { + return __cosmetics; } + __cosmetics = (async () => { + try { + const response = await fetch(`${getApiBase()}/cosmetics.json`); + if (!response.ok) { + console.error(`HTTP error! status: ${response.status}`); + return null; + } + const result = CosmeticsSchema.safeParse(await response.json()); + if (!result.success) { + console.error(`Invalid cosmetics: ${result.error.message}`); + return null; + } + return result.data; + } catch (error) { + console.error("Error getting cosmetics:", error); + return null; + } + })(); + return __cosmetics; } export function patternRelationship( diff --git a/src/client/PatternInput.ts b/src/client/PatternInput.ts index 7c435c63c..755c7c834 100644 --- a/src/client/PatternInput.ts +++ b/src/client/PatternInput.ts @@ -7,20 +7,6 @@ import { renderPatternPreview } from "./components/PatternButton"; import { fetchCosmetics } from "./Cosmetics"; import { translateText } from "./Utils"; -// Module-level cosmetics cache to avoid refetching on every component mount -let cosmeticsCache: Promise | null = null; - -function getCachedCosmetics(): Promise { - if (!cosmeticsCache) { - const fetchPromise = fetchCosmetics(); - cosmeticsCache = fetchPromise.catch((err) => { - cosmeticsCache = null; - throw err; - }); - } - return cosmeticsCache; -} - @customElement("pattern-input") export class PatternInput extends LitElement { @state() public pattern: PlayerPattern | null = null; @@ -63,7 +49,7 @@ export class PatternInput extends LitElement { super.connectedCallback(); this._abortController = new AbortController(); this.isLoading = true; - const cosmetics = await getCachedCosmetics(); + const cosmetics = await fetchCosmetics(); if (!this.isConnected) return; this.cosmetics = cosmetics; this.updateFromSettings();