From 32246f632ef3b8e603ebceb8bae0a031a109702e Mon Sep 17 00:00:00 2001 From: fullex <0xfullex@gmail.com> Date: Sun, 11 Jan 2026 21:23:08 +0800 Subject: [PATCH] refactor(useDataApi): enhance globalMutate and cache key matching - Updated globalMutate calls to use createKeyMatcher and createMultiKeyMatcher for improved cache key handling. - Modified return types in buildSWRKey to support optional query parameters. - Added createKeyMatcher and createMultiKeyMatcher functions to facilitate matching of SWR cache keys by path and multiple paths, respectively. --- src/renderer/src/data/hooks/useDataApi.ts | 39 ++++++++++++++++++----- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/src/renderer/src/data/hooks/useDataApi.ts b/src/renderer/src/data/hooks/useDataApi.ts index 41aa80a016..0c94048a56 100644 --- a/src/renderer/src/data/hooks/useDataApi.ts +++ b/src/renderer/src/data/hooks/useDataApi.ts @@ -313,7 +313,7 @@ export function useMutation globalMutate(key))) + await globalMutate(createMultiKeyMatcher(optionsRef.current.refresh)) } }, onError: (error) => optionsRef.current?.onError?.(error), @@ -329,7 +329,7 @@ export function useMutation true) } else if (typeof keys === 'string') { - await mutate(keys) + await mutate(createKeyMatcher(keys)) } else if (Array.isArray(keys)) { - await Promise.all(keys.map((key) => mutate(key))) + await mutate(createMultiKeyMatcher(keys)) } } @@ -703,12 +703,12 @@ function createApiFetcher>( path: TPath, query?: TQuery -): [TPath] | [TPath, TQuery] { +): [TPath, TQuery?] { if (query && Object.keys(query).length > 0) { return [path, query] } @@ -729,3 +729,26 @@ function getFetcher([path, query]: [TPath, Query const apiFetcher = createApiFetcher('GET') return apiFetcher(path, { query }) } + +/** + * Create a filter function that matches SWR cache keys by path. + * Matches both [path] and [path, query] formats. + * + * @internal + * @param pathToMatch - The API path to match against cache keys + * @returns Filter function for use with SWR's mutate + */ +function createKeyMatcher(pathToMatch: string): (key: unknown) => boolean { + return (key) => Array.isArray(key) && key[0] === pathToMatch +} + +/** + * Create a filter function that matches multiple paths. + * + * @internal + * @param paths - Array of API paths to match against cache keys + * @returns Filter function for use with SWR's mutate + */ +function createMultiKeyMatcher(paths: string[]): (key: unknown) => boolean { + return (key) => Array.isArray(key) && paths.includes(key[0] as string) +}