Skip to content

Commit

Permalink
Use simple TTL cache for theme to avoid refetch
Browse files Browse the repository at this point in the history
  • Loading branch information
Willdotwhite committed Mar 20, 2024
1 parent 986d5ed commit ab8150d
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions ui/src/common/components/JamSpecificStyling.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,40 @@ type Jam = {
logoLargeUrl: string,
logoStackedUrl: string,
styles: object,
expiry: number,
}

export const JamSpecificThemeContext = createContext<Jam>({
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<Jam>()

// 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'])
})
Expand Down

0 comments on commit ab8150d

Please sign in to comment.