mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-08 02:52:07 +08:00
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.
58 lines
1.6 KiB
TypeScript
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,
|
|
}
|
|
}
|