Cache enabled value for reloads, use real data for service config

This commit is contained in:
Eric Bailey
2024-12-16 17:41:00 -06:00
parent 409809a4b3
commit 6437e7b4c5
3 changed files with 19 additions and 11 deletions
+5 -5
View File
@@ -1,5 +1,6 @@
import {useQuery} from '@tanstack/react-query'
import {STALE} from '#/state/queries'
import {useAgent} from '#/state/session'
type ServiceConfig = {
@@ -11,16 +12,16 @@ type ServiceConfig = {
export function useServiceConfigQuery() {
const agent = useAgent()
return useQuery<ServiceConfig>({
refetchOnWindowFocus: true,
staleTime: STALE.MINUTES.ONE,
queryKey: ['service-config'],
queryFn: async () => {
try {
const {data} = await agent.api.app.bsky.unspecced.getConfig()
return {
checkEmailConfirmed: Boolean(data.checkEmailConfirmed),
// TODO
trendingTopicsEnabled: true, // Boolean(data.trendingTopicsEnabled),
// TODO
trendingTopicsLangs: ['en'], // data.trendingTopicsLangs ?? [],
trendingTopicsEnabled: Boolean(data.trendingTopicsEnabled),
trendingTopicsLangs: (data.trendingTopicsLangs ?? []) as string[],
}
} catch (e) {
return {
@@ -30,6 +31,5 @@ export function useServiceConfigQuery() {
}
}
},
staleTime: 5 * 60 * 1000,
})
}
+13 -6
View File
@@ -2,6 +2,7 @@ import React from 'react'
import {useLanguagePrefs} from '#/state/preferences/languages'
import {useServiceConfigQuery} from '#/state/queries/service-config'
import {device} from '#/storage'
type Context = {
enabled: boolean
@@ -13,17 +14,23 @@ const Context = React.createContext<Context>({
export function Provider({children}: React.PropsWithChildren<{}>) {
const langPrefs = useLanguagePrefs()
const {data: config} = useServiceConfigQuery()
// refetches at most every minute
const {data: config, isLoading: isInitialLoad} = useServiceConfigQuery()
const ctx = React.useMemo<Context>(() => {
// TODO maybe default to true
// previously cached value
const cachedEnabled = device.get(['trendingBetaEnabled'])
if (isInitialLoad) {
return {enabled: Boolean(cachedEnabled)}
}
const serviceEnabled = Boolean(config?.trendingTopicsEnabled)
const languageIsSupported = langPrefs.contentLanguages.some(lang => {
return (config?.trendingTopicsLangs ?? []).includes(lang)
})
return {
enabled: serviceEnabled && languageIsSupported,
}
}, [config, langPrefs])
const enabled = serviceEnabled && languageIsSupported
// update cache
device.set(['trendingBetaEnabled'], enabled)
return {enabled}
}, [isInitialLoad, config, langPrefs])
return <Context.Provider value={ctx}>{children}</Context.Provider>
}
+1
View File
@@ -8,4 +8,5 @@ export type Device = {
geolocation?: {
countryCode: string | undefined
}
trendingBetaEnabled: boolean
}