Eh let's let RQ handle refetch and retries
This commit is contained in:
+21
-20
@@ -1,7 +1,6 @@
|
||||
import {createContext, useContext} from 'react'
|
||||
import {QueryClient, useQuery} from '@tanstack/react-query'
|
||||
|
||||
import {networkRetry} from '#/lib/async/retry'
|
||||
import {APP_CONFIG_URL} from '#/env'
|
||||
|
||||
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> {
|
||||
try {
|
||||
if (!fetchAppConfigPromise) {
|
||||
fetchAppConfigPromise = networkRetry(
|
||||
3,
|
||||
async () => {
|
||||
const r = await fetch(`${APP_CONFIG_URL}/config`)
|
||||
if (!r.ok) throw new Error(await r.text())
|
||||
const data = await r.json()
|
||||
return data
|
||||
},
|
||||
1e3,
|
||||
)
|
||||
fetchAppConfigPromise = (async () => {
|
||||
const r = await fetch(`${APP_CONFIG_URL}/config`)
|
||||
if (!r.ok) throw new Error(await r.text())
|
||||
const data = await r.json()
|
||||
return data
|
||||
})()
|
||||
}
|
||||
return await fetchAppConfigPromise
|
||||
} catch {
|
||||
return null
|
||||
} catch (e) {
|
||||
fetchAppConfigPromise = undefined
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
const Context = createContext<AppConfigResponse>(DEFAULT_APP_CONFIG_RESPONSE)
|
||||
|
||||
export function Provider({children}: React.PropsWithChildren<{}>) {
|
||||
const {data} = useQuery(
|
||||
const {data} = useQuery<AppConfigResponse | null>(
|
||||
{
|
||||
staleTime: Infinity,
|
||||
gcTime: Infinity,
|
||||
queryKey: appConfigQueryKey,
|
||||
refetchInterval: query => {
|
||||
// refetch regularly if fetch failed, otherwise never refetch
|
||||
return query.state.status === 'error' ? 60e3 : Infinity
|
||||
},
|
||||
async queryFn() {
|
||||
return fetchAppConfig()
|
||||
},
|
||||
@@ -71,10 +70,12 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
|
||||
}
|
||||
|
||||
export async function prefetchAppConfig() {
|
||||
const data = await fetchAppConfig()
|
||||
if (data) {
|
||||
qc.setQueryData(appConfigQueryKey, data)
|
||||
}
|
||||
try {
|
||||
const data = await fetchAppConfig()
|
||||
if (data) {
|
||||
qc.setQueryData(appConfigQueryKey, data)
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function useAppConfig() {
|
||||
|
||||
Reference in New Issue
Block a user