mirror of
https://github.com/lobehub/lobe-chat.git
synced 2026-06-15 12:10:16 +00:00
🐛 fix: slove the mutate not work problem (#10947)
fix: slove the mutate not work problem
This commit is contained in:
+21
-11
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user