使用apollo3-cache-persist时缓存自动清除,持久化功能失效求助
Hey there! Let's figure out why your Apollo cache keeps getting cleared right after initialization—this is a tricky one but totally fixable. Here are the most common causes and solutions I've used to resolve similar problems:
1. Check for Accidental Cache Resets
First, do a full search of your codebase for these two methods:
cache.reset()client.resetStore()
Both of these will wipe your entire cache and sync that clear to your persistent storage (localStorage in your case). It’s easy to accidentally call these in a component’s useEffect or initialization logic without realizing the impact.
2. Tweak Persist Cache Configuration
Your current setup is close, but adding a few extra config options can prevent unexpected clears:
- Explicitly set
skipRestore: false(it’s default, but making it explicit ensures the cache restores properly) - Add a
flushIntervalto avoid frequent, conflicting writes to localStorage
Update your persistCache call like this:
persistCache({ cache, storage: new LocalStorageWrapper(window.localStorage), debug: true, skipRestore: false, // Ensure cache is restored from localStorage persistOptions: { flushInterval: 1000, // Delay writes to avoid race conditions }, })
3. Verify Cache Restore & Persist Logs
Since you have debug: true enabled, keep an eye on your browser’s console for these key logs:
[apollo-cache-persist] Restored cache from storage: Confirms the cache loaded correctly from localStorage[apollo-cache-persist] Persisted cache to storage: Shows when data is saved- Any
Cleared cacheor error messages: These will point directly to what’s triggering the clear
Also, check your browser’s Application > Local Storage tab:
- See if the cache data appears on initial load, then watch when it disappears—this will tell you exactly when the clear happens.
4. Add Basic Type Policies to InMemoryCache
Sometimes the default cache merging logic can accidentally overwrite or clear data if your schema has nested or repeated fields. Adding simple type policies ensures data is merged instead of replaced:
const cache = new InMemoryCache({ typePolicies: { Query: { fields: { // Replace with your actual query fields (e.g., users, posts) users: { merge: true }, currentUser: { merge: true }, }, }, }, });
5. Rule Out External LocalStorage Modifications
Check if any other part of your app is directly modifying window.localStorage—like a utility function that clears storage on logout, or a third-party library that’s wiping keys. Even a localStorage.clear() call elsewhere will erase your Apollo cache data.
Updated Full Example Code
Here’s how all these fixes come together in your code:
import { persistCache, LocalStorageWrapper } from 'apollo3-cache-persist'; import { createHttpLink, InMemoryCache, ApolloClient, ApolloProvider } from '@apollo/client'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import App from './App'; const httpLink = createHttpLink({ uri: 'http://localhost:4000/' }); // Configure cache with type policies to prevent accidental overwrites const cache = new InMemoryCache({ typePolicies: { Query: { fields: { // Add your actual query fields here // Example: getUser: { merge: true }, }, }, }, }); persistCache({ cache, storage: new LocalStorageWrapper(window.localStorage), debug: true, skipRestore: false, persistOptions: { flushInterval: 1000, }, }) .then(() => { const client = new ApolloClient({ link: httpLink, cache, connectToDevTools: true, }); // Optional: Watch cache changes to debug unexpected updates cache.watch({ callback: (data) => { console.log('Cache updated:', data); }, }); ReactDOM.render( <ApolloProvider client={client}> <BrowserRouter> <App /> </BrowserRouter> </ApolloProvider>, document.getElementById('root') ); }) .catch((err) => { console.error('Failed to set up persistent cache:', err); });
Start with checking the console logs and localStorage first—those will give you the fastest clues about what’s causing the clear.
内容的提问来源于stack exchange,提问作者Rahul PM




