🐛 fix: slove the mutate not work problem (#10947)

fix: slove the mutate not work problem
This commit is contained in:
Shinji-Li
2025-12-24 22:42:50 +08:00
committed by GitHub
parent 0e49d11621
commit 78ca5ebed5
+21 -11
View File
@@ -4,7 +4,7 @@
* When using a custom cache provider with SWRConfig, the global `mutate` from 'swr'
* becomes a no-op because it can't access the scoped cache.
*
* This module provides a scoped mutate function that works with custom cache providers.
* This module stores the scoped mutate function from SWRConfig for use outside React components.
* The mutate function is initialized when the SWRConfig component mounts.
*
* @see https://github.com/vercel/swr/issues/2799
@@ -20,27 +20,37 @@
*/
import type { ScopedMutator } from 'swr/_internal';
// Global scoped mutate reference, set when SWRConfig mounts
let scopedMutate: ScopedMutator | null = null;
// Mutable container to hold the scoped mutate reference
// Using an object allows us to update the reference while keeping the same export
const mutateRef: { current: ScopedMutator | null } = { current: null };
/**
* Set the scoped mutate function from SWRConfig
* Called internally by SWRProvider on mount
*/
export const setScopedMutate = (m: ScopedMutator) => {
scopedMutate = m;
mutateRef.current = m;
};
/**
* Get the scoped mutate function
* Returns the actual mutate function from useSWRConfig(), not a wrapper
*/
export const getMutate = (): ScopedMutator => {
if (!mutateRef.current) {
console.warn('[SWR] Scoped mutate not initialized, this may cause cache sync issues');
// Return a no-op function that returns empty array
return (() => []) as unknown as ScopedMutator;
}
return mutateRef.current;
};
/**
* Scoped mutate function that works with custom cache providers
* This is the actual mutate function from useSWRConfig(), stored globally
*
* Use this instead of `import { mutate } from 'swr'` when using localStorage cache provider
*/
export const mutate: ScopedMutator = (async (key: any, data?: any, opts?: any) => {
if (!scopedMutate) {
console.warn('[SWR] Scoped mutate not initialized, this may cause cache sync issues');
return [];
}
return await scopedMutate(key, data, opts);
export const mutate: ScopedMutator = (async (...args: Parameters<ScopedMutator>) => {
return await getMutate()(...args);
}) as ScopedMutator;