Files
clash-verge-rev/src/hooks/use-verge.ts
T
Tunglies 1552f8e2f9 fix(events): close run-state race and restore single error toasts
Self-review findings: the bus now re-reads the run-state snapshot in
onSubscribed so an event racing the store's initial read cannot leave a
stale snapshot (the ordering the old layout listener guaranteed), and the
patch hooks pass errorNotice:false so GuardState/page handlers remain the
only error toast, matching the pre-migration behavior.
2026-10-01 14:34:17 +08:00

58 lines
1.6 KiB
TypeScript

import { useCallback } from 'react'
import { getVergeConfig, patchVergeConfig } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { getPreloadConfig, setPreloadConfig } from '@/services/preload'
import { setCacheData, useQuery } from '@/services/query-client'
export const useVerge = () => {
const initialVergeConfig = getPreloadConfig()
const { data: verge, refetch } = useQuery({
queryKey: ['getVergeConfig'],
queryFn: async () => {
const config = await getVergeConfig()
setPreloadConfig(config)
return config
},
initialData: initialVergeConfig ?? undefined,
revalidateOnMount: initialVergeConfig ? false : undefined,
staleTime: 5000,
})
const mutateVerge = (
updaterOrData?:
| IVergeConfig
| ((prev: IVergeConfig | undefined) => IVergeConfig | undefined)
| undefined,
_revalidate?: boolean,
) => {
if (updaterOrData === undefined) {
void refetch()
return
}
void setCacheData<IVergeConfig>(
['getVergeConfig'],
typeof updaterOrData === 'function'
? (current) => updaterOrData(current ?? verge)
: updaterOrData,
)
}
// Callers own the error toast (GuardState onCatch / page onError), so the
// funnel must not add a second one.
const patchVerge = useCallback(async (value: Partial<IVergeConfig>) => {
await mutate(() => patchVergeConfig(value), {
id: 'patch-verge-config',
revalidate: [['getVergeConfig']],
errorNotice: false,
})
}, [])
return {
verge,
mutateVerge,
patchVerge,
}
}