Eh let's let RQ handle refetch and retries

This commit is contained in:
Eric Bailey
2026-02-16 10:51:49 -06:00
parent 85ca5ccf22
commit cd8f8c60b9
+21 -20
View File
@@ -1,7 +1,6 @@
import {createContext, useContext} from 'react' import {createContext, useContext} from 'react'
import {QueryClient, useQuery} from '@tanstack/react-query' import {QueryClient, useQuery} from '@tanstack/react-query'
import {networkRetry} from '#/lib/async/retry'
import {APP_CONFIG_URL} from '#/env' import {APP_CONFIG_URL} from '#/env'
const qc = new QueryClient() const qc = new QueryClient()
@@ -27,36 +26,36 @@ export const DEFAULT_APP_CONFIG_RESPONSE: AppConfigResponse = {
}, },
} }
let fetchAppConfigPromise: Promise<AppConfigResponse> let fetchAppConfigPromise: Promise<AppConfigResponse> | undefined
async function fetchAppConfig(): Promise<AppConfigResponse | null> { async function fetchAppConfig(): Promise<AppConfigResponse | null> {
try { try {
if (!fetchAppConfigPromise) { if (!fetchAppConfigPromise) {
fetchAppConfigPromise = networkRetry( fetchAppConfigPromise = (async () => {
3, const r = await fetch(`${APP_CONFIG_URL}/config`)
async () => { if (!r.ok) throw new Error(await r.text())
const r = await fetch(`${APP_CONFIG_URL}/config`) const data = await r.json()
if (!r.ok) throw new Error(await r.text()) return data
const data = await r.json() })()
return data
},
1e3,
)
} }
return await fetchAppConfigPromise return await fetchAppConfigPromise
} catch { } catch (e) {
return null fetchAppConfigPromise = undefined
throw e
} }
} }
const Context = createContext<AppConfigResponse>(DEFAULT_APP_CONFIG_RESPONSE) const Context = createContext<AppConfigResponse>(DEFAULT_APP_CONFIG_RESPONSE)
export function Provider({children}: React.PropsWithChildren<{}>) { export function Provider({children}: React.PropsWithChildren<{}>) {
const {data} = useQuery( const {data} = useQuery<AppConfigResponse | null>(
{ {
staleTime: Infinity, staleTime: Infinity,
gcTime: Infinity,
queryKey: appConfigQueryKey, queryKey: appConfigQueryKey,
refetchInterval: query => {
// refetch regularly if fetch failed, otherwise never refetch
return query.state.status === 'error' ? 60e3 : Infinity
},
async queryFn() { async queryFn() {
return fetchAppConfig() return fetchAppConfig()
}, },
@@ -71,10 +70,12 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
} }
export async function prefetchAppConfig() { export async function prefetchAppConfig() {
const data = await fetchAppConfig() try {
if (data) { const data = await fetchAppConfig()
qc.setQueryData(appConfigQueryKey, data) if (data) {
} qc.setQueryData(appConfigQueryKey, data)
}
} catch {}
} }
export function useAppConfig() { export function useAppConfig() {