From ab8150d4b9f2d502679dd04059516c88ef6678ac Mon Sep 17 00:00:00 2001 From: WillDotWhite Date: Wed, 20 Mar 2024 23:58:49 +0000 Subject: [PATCH] Use simple TTL cache for theme to avoid refetch --- .../common/components/JamSpecificStyling.tsx | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/ui/src/common/components/JamSpecificStyling.tsx b/ui/src/common/components/JamSpecificStyling.tsx index 1deb28e..41bdc47 100644 --- a/ui/src/common/components/JamSpecificStyling.tsx +++ b/ui/src/common/components/JamSpecificStyling.tsx @@ -6,28 +6,40 @@ type Jam = { logoLargeUrl: string, logoStackedUrl: string, styles: object, + expiry: number, } export const JamSpecificThemeContext = createContext({ jamId: "", logoLargeUrl: "", logoStackedUrl: "", - styles: {} + styles: {}, + expiry: Date.now() }) export const JamSpecificStyling: React.FC<{children: any}> = ({children}) => { const jamId = useMatch("/:jamId/:postId?")?.params.jamId!!; const [activeTheme, setActiveTheme] = useState() - // TODO: Cache and avoid refetch - // TODO: TTL for styles? useEffect(() => { if (!jamId) return + const cachedThemeStr = localStorage.getItem(`theme_${jamId}`) + if (cachedThemeStr) { + const cachedTheme = JSON.parse(cachedThemeStr) as Jam + if (cachedTheme.expiry > Date.now()) { + setActiveTheme(cachedTheme) + return + } + } + fetch(`${import.meta.env.VITE_API_URL}/jams/${jamId}`) .then(async res => { const data = await res.json() - if (res.ok) return data as Jam + if (res.ok) { + data.expiry = Date.now() + 6*60*60*1000 // 6 hours expiry + return data as Jam + } return Promise.reject(data['message']) })