### Install apollo3-cache-persist Source: https://github.com/apollographql/apollo-cache-persist/blob/master/README.md Installs the apollo3-cache-persist library using either npm or yarn package managers. ```shell npm install --save apollo3-cache-persist ``` ```shell yarn add apollo3-cache-persist ``` -------------------------------- ### Multiple Storage Providers Configuration Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt An example demonstrating how to configure apollo3-cache-persist to use different storage providers based on the runtime environment (web or React Native). It dynamically selects between `LocalStorageWrapper`, `SessionStorageWrapper`, `LocalForageWrapper`, and `AsyncStorageWrapper`. Dependencies include Apollo Client and apollo3-cache-persist. ```javascript import { InMemoryCache } from '@apollo/client/core'; import { persistCache, LocalStorageWrapper, SessionStorageWrapper, LocalForageWrapper, AsyncStorageWrapper } from 'apollo3-cache-persist'; const cache = new InMemoryCache(); // Choose storage based on environment let storage; if (typeof window !== 'undefined') { // Web environment if (window.localStorage) { // Persistent storage storage = new LocalStorageWrapper(window.localStorage); } else if (window.sessionStorage) { // Session-only storage storage = new SessionStorageWrapper(window.sessionStorage); } } else { // React Native const AsyncStorage = require('@react-native-async-storage/async-storage').default; storage = new AsyncStorageWrapper(AsyncStorage); } await persistCache({ cache, storage, maxSize: 2097152, debug: process.env.NODE_ENV === 'development' }); ``` -------------------------------- ### Custom Persistence Trigger Example Source: https://github.com/apollographql/apollo-cache-persist/blob/master/docs/advanced-usage.md Provides an example of a custom persistence trigger function for `apollo-cache-persist`. This function accepts a `persist` callback and returns an uninstall function. The example demonstrates persisting the cache every 10 seconds using `setInterval`, with a caution against this specific interval-based approach. ```javascript // This code is for illustration only. // We do not recommend persisting on an interval. const trigger = persist => { // Call `persist` every 10 seconds. const interval = setInterval(persist, 10000); // Return function to uninstall this custom trigger. return () => clearInterval(interval); }; // TypeScript signature for reference: // (persist: () => void) => (() => void) ``` -------------------------------- ### Synchronous Cache Persistence in React Source: https://github.com/apollographql/apollo-cache-persist/blob/master/docs/faq.md This example shows how to use `persistCacheSync` for synchronous cache persistence, suitable for small cache sizes and synchronous storage like `window.localStorage`. It's noted that this method blocks UI rendering until the cache is restored and is best suited for demo applications. ```javascript import { InMemoryCache } from '@apollo/client/core'; import { persistCacheSync, LocalStorageWrapper } from 'apollo3-cache-persist'; const cache = new InMemoryCache({...}); persistCacheSync({ cache, storage: new LocalStorageWrapper(window.localStorage), }); ``` -------------------------------- ### persistCache - Simple Async Cache Persistence Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Automatically persists and restores Apollo cache using the provided storage provider. This function simplifies cache persistence by handling most of the setup and operations automatically. ```APIDOC ## persistCache - Simple Async Cache Persistence ### Description Automatically persists and restores Apollo cache using the provided storage provider. Returns a promise that resolves when the cache is restored from storage. ### Method `persistCache(options)` ### Parameters #### Request Body - **cache** (InMemoryCache) - Required - The Apollo Client cache instance to persist. - **storage** (StorageWrapper) - Required - An instance of a storage wrapper (e.g., `LocalStorageWrapper`, `AsyncStorageWrapper`). - **debounce** (number) - Optional - The delay in milliseconds after the last write operation before persisting the cache. Defaults to 1000ms. - **maxSize** (number) - Optional - The maximum size of the cache in bytes. Defaults to 1048576 (1MB). - **key** (string) - Optional - The key used to store the cache data in the storage provider. Defaults to 'apollo-cache-persist'. - **debug** (boolean) - Optional - Enables console logging for debugging purposes. Defaults to false. ### Request Example ```javascript import { InMemoryCache } from '@apollo/client/core'; import { persistCache, LocalStorageWrapper } from 'apollo3-cache-persist'; import { ApolloClient } from '@apollo/client'; const cache = new InMemoryCache(); await persistCache({ cache, storage: new LocalStorageWrapper(window.localStorage), debounce: 1000, maxSize: 1048576, key: 'apollo-cache-persist', debug: true }); const client = new ApolloClient({ uri: 'https://api.example.com/graphql', cache }); ``` ### Response #### Success Response (Promise) Resolves when the cache has been successfully restored from storage. ``` -------------------------------- ### Selective Cache Persistence with persistenceMapper Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Filter or transform cache data before persistence using a mapper function for fine-grained control over what gets stored. This is useful for excluding sensitive or temporary data. ```javascript import { InMemoryCache } from '@apollo/client/core'; import { CachePersistor, LocalStorageWrapper } from 'apollo3-cache-persist'; const cache = new InMemoryCache(); const persistor = new CachePersistor({ cache, storage: new LocalStorageWrapper(window.localStorage), persistenceMapper: async (data) => { // Filter out sensitive or temporary data const filtered = { ...data }; // Remove specific query results if (filtered.ROOT_QUERY) { delete filtered.ROOT_QUERY.currentUser; delete filtered.ROOT_QUERY.temporaryData; } // Remove all mutations if (filtered.ROOT_MUTATION) { delete filtered.ROOT_MUTATION; } console.log('Persisting filtered cache:', Object.keys(filtered)); return filtered; } }); await persistor.restore(); ``` -------------------------------- ### CachePersistor with Persistence Mapper Source: https://github.com/apollographql/apollo-cache-persist/blob/master/docs/advanced-usage.md Illustrates how to use the `persistenceMapper` option with `CachePersistor` to selectively persist parts of the Apollo cache. This function allows for filtering cached data and queries before they are stored, providing custom control over what gets persisted. ```typescript const persistor = new CachePersistor({ ... persistenceMapper: async (data: any) => { // filter your cached data and queries return filteredData; }, }) ``` -------------------------------- ### React Apollo Client Initialization with Persisted Cache (Hooks) Source: https://github.com/apollographql/apollo-cache-persist/blob/master/docs/faq.md This snippet demonstrates how to initialize an Apollo Client instance in a React application using hooks, ensuring the cache is persisted and restored before rendering the rest of the application. It utilizes `persistCache` with `LocalStorageWrapper` and `useEffect` to handle the asynchronous nature of cache restoration. ```javascript import React, { useEffect, useState } from 'react'; import { ApolloClient, ApolloProvider } from '@apollo/client'; import { InMemoryCache } from '@apollo/client/core'; import { LocalStorageWrapper, persistCache } from 'apollo3-cache-persist'; const App = () => { const [client, setClient] = useState(); useEffect(() => { async function init() { const cache = new InMemoryCache(); await persistCache({ cache, storage: new LocalStorageWrapper(window.localStorage), }); setClient( new ApolloClient({ cache, }), ); } init().catch(console.error); }, []); if (!client) { return

Initializing app...

; } return ( {/* the rest of your app goes here */} ); }; export default App; ``` -------------------------------- ### CachePersistor Methods for Manual Control Source: https://github.com/apollographql/apollo-cache-persist/blob/master/docs/advanced-usage.md Demonstrates the methods available on an instantiated `CachePersistor` object, allowing for direct control over cache restoration, persistence, purging, pausing, resuming, and log retrieval. These methods provide fine-grained management of the cache persistence lifecycle. ```javascript const persistor = new CachePersistor({...}); persistor.restore(); // Immediately restore the cache. Returns a Promise. persistor.persist(); // Immediately persist the cache. Returns a Promise. persistor.purge(); // Immediately purge the stored cache. Returns a Promise. persistor.pause(); // Pause persistence. Triggers are ignored while paused. persistor.resume(); // Resume persistence. persistor.remove(); // Remove the persistence trigger. Manual persistence required after calling this. // Obtain the most recent 30 persistor loglines. // `print: true` will print them to the console; `false` will return an array. persistor.getLogs(print); // Obtain the current persisted cache size in bytes. Returns a Promise. // Resolves to 0 for empty and `null` when `serialize: true` is in use. persistor.getSize(); ``` -------------------------------- ### LocalStorageWrapper - Web Browser Persistence Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Wraps the browser's localStorage API for synchronous cache persistence in web applications. This wrapper allows `apollo3-cache-persist` to interact with `window.localStorage`. ```APIDOC ## LocalStorageWrapper - Web Browser Persistence ### Description Wraps browser localStorage API for synchronous cache persistence in web applications. ### Method `new LocalStorageWrapper(localStorage)` ### Parameters #### Request Body - **localStorage** (Storage) - Required - The browser's localStorage object (e.g., `window.localStorage`). ### Request Example ```javascript import { InMemoryCache } from '@apollo/client/core'; import { CachePersistor, LocalStorageWrapper } from 'apollo3-cache-persist'; const cache = new InMemoryCache(); const persistor = new CachePersistor({ cache, storage: new LocalStorageWrapper(window.localStorage), key: 'my-app-apollo-cache', trigger: 'write', debounce: 500 }); await persistor.restore(); const size = await persistor.getSize(); if (size && size > 5000000) { // 5MB console.warn('Cache exceeds 5MB'); await persistor.purge(); } ``` ``` -------------------------------- ### Persist Cache in Web Applications Source: https://github.com/apollographql/apollo-cache-persist/blob/master/README.md Shows how to persist the Apollo Client cache in a web application using browser's localStorage. Similar to React Native, awaiting persistCache before ApolloClient initialization is recommended for proper data restoration. ```javascript import { InMemoryCache } from '@apollo/client/core'; import { persistCache, LocalStorageWrapper } from 'apollo3-cache-persist'; const cache = new InMemoryCache({...}); // await before instantiating ApolloClient, else queries might run before the cache is persisted await persistCache({ cache, storage: new LocalStorageWrapper(window.localStorage), }); // Continue setting up Apollo as usual. const client = new ApolloClient({ cache, ... }); ``` -------------------------------- ### Persist Apollo Cache with Web localStorage (JavaScript) Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Wraps the browser localStorage API for synchronous cache persistence in web applications. It allows configuration of cache, storage, key, trigger, and debounce, and provides methods for restore, getSize, and purge. ```javascript import { InMemoryCache } from '@apollo/client/core'; import { CachePersistor, LocalStorageWrapper } from 'apollo3-cache-persist'; const cache = new InMemoryCache(); const persistor = new CachePersistor({ cache, storage: new LocalStorageWrapper(window.localStorage), key: 'my-app-apollo-cache', trigger: 'write', debounce: 500 // Persist 500ms after last write }); await persistor.restore(); // Check cache size before persisting large datasets const size = await persistor.getSize(); if (size && size > 5000000) { // 5MB console.warn('Cache exceeds 5MB'); await persistor.purge(); } ``` -------------------------------- ### Advanced Apollo Cache Persistence Control (JavaScript) Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Provides manual control over cache persistence operations. It allows for manual persist, restore, purge, and trigger management. Key methods include restore, persist, purge, pause, resume, remove, getLogs, and getSize. ```javascript import { InMemoryCache } from '@apollo/client/core'; import { CachePersistor, LocalStorageWrapper } from 'apollo3-cache-persist'; import { ApolloClient } from '@apollo/client'; const cache = new InMemoryCache(); // Create persistor instance const persistor = new CachePersistor({ cache, storage: new LocalStorageWrapper(window.localStorage), trigger: 'write', // 'write' | 'background' | false | custom function debug: true }); // Manually restore cache await persistor.restore(); const client = new ApolloClient({ uri: 'https://api.example.com/graphql', cache }); // Manual persistence operations await persistor.persist(); // Force immediate persist await persistor.purge(); // Clear all persisted data // Trigger control persistor.pause(); // Stop automatic persistence persistor.resume(); // Resume automatic persistence persistor.remove(); // Permanently disable automatic persistence // Debugging const logs = persistor.getLogs(); // Get log array persistor.getLogs(true); // Print logs to console const sizeInBytes = await persistor.getSize(); // Get cache size ``` -------------------------------- ### Complete React App Cache Persistence Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt A full-featured React application demonstrating cache persistence with Apollo Client. It includes user controls for clearing, pausing, and resuming cache persistence. The configuration uses `LocalStorageWrapper` and persists on 'write' triggers. Dependencies include React, Apollo Client, and apollo3-cache-persist. ```javascript import { useEffect, useState, useCallback } from 'react'; import { ApolloClient, ApolloProvider, useQuery, gql, InMemoryCache } from '@apollo/client'; import { CachePersistor, LocalStorageWrapper } from 'apollo3-cache-persist'; const QUERY = gql` query GetData { items { id name description } } `; const DataComponent = () => { const { data, loading, error } = useQuery(QUERY, { fetchPolicy: 'cache-and-network' // Use cache but also fetch fresh data }); if (!data) { if (loading) return
Loading initial data...
; if (error) return
Error: {error.message}
; return
No data
; } return (
{loading &&
Refreshing data...
} {data.items.map(item => (

{item.name}

{item.description}

))}
); }; const App = () => { const [client, setClient] = useState(null); const [persistor, setPersistor] = useState(null); useEffect(() => { async function init() { const cache = new InMemoryCache(); const newPersistor = new CachePersistor({ cache, storage: new LocalStorageWrapper(window.localStorage), debug: true, trigger: 'write', maxSize: 1048576 // 1MB }); // Restore persisted cache await newPersistor.restore(); setPersistor(newPersistor); setClient( new ApolloClient({ uri: 'https://api.example.com/graphql', cache }) ); } init().catch(console.error); }, []); const handleClearCache = useCallback(async () => { if (persistor) { await persistor.purge(); window.location.reload(); } }, [persistor]); const handlePauseCache = useCallback(() => { if (persistor) { persistor.pause(); console.log('Cache persistence paused'); } }, [persistor]); const handleResumeCache = useCallback(() => { if (persistor) { persistor.resume(); console.log('Cache persistence resumed'); } }, [persistor]); if (!client) { return
Initializing application...
; } return (

Apollo Cache Persist Demo

); }; export default App; ``` -------------------------------- ### Synchronous Cache Persistence with persistCacheSync Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Synchronously restore cache using storage providers with synchronous APIs, useful for immediate cache availability without async/await. This method is only compatible with synchronous storage providers. ```javascript import { InMemoryCache } from '@apollo/client/core'; import { persistCacheSync, LocalStorageWrapper } from 'apollo3-cache-persist'; const cache = new InMemoryCache(); // Synchronously restore cache (no await needed) persistCacheSync({ cache, storage: new LocalStorageWrapper(window.localStorage) }); // Cache is immediately available const client = new ApolloClient({ uri: 'https://api.example.com/graphql', cache }); // Note: Only works with synchronous storage providers // AsyncStorage and other async providers require persistCache() ``` -------------------------------- ### Advanced Synchronous Cache Persistor Operations Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Provides advanced synchronous persistence control for storage providers with synchronous APIs. It offers methods like restoreSync, persist, purge, pause, and resume for comprehensive cache management. ```javascript import { InMemoryCache } from '@apollo/client/core'; import { SynchronousCachePersistor, LocalStorageWrapper } from 'apollo3-cache-persist'; const cache = new InMemoryCache(); const persistor = new SynchronousCachePersistor({ cache, storage: new LocalStorageWrapper(window.localStorage), maxSize: 5242880, // 5MB debug: true }); // Synchronous restore persistor.restoreSync(); // Async operations still available await persistor.persist(); await persistor.purge(); // All control methods work as with CachePersistor persistor.pause(); persistor.resume(); ``` -------------------------------- ### AsyncStorageWrapper - React Native Persistence Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Wraps React Native's AsyncStorage for Apollo cache persistence. This wrapper provides a compatible interface for `apollo3-cache-persist` to use with React Native's asynchronous storage. ```APIDOC ## AsyncStorageWrapper - React Native Persistence ### Description Wraps React Native's AsyncStorage for Apollo cache persistence with promise-based async operations. ### Method `new AsyncStorageWrapper(asyncStorage)` ### Parameters #### Request Body - **asyncStorage** (object) - Required - The AsyncStorage instance from '@react-native-async-storage/async-storage'. ### Request Example ```javascript import AsyncStorage from '@react-native-async-storage/async-storage'; import { InMemoryCache } from '@apollo/client/core'; import { persistCache, AsyncStorageWrapper } from 'apollo3-cache-persist'; import { ApolloClient } from '@apollo/client'; const cache = new InMemoryCache(); await persistCache({ cache, storage: new AsyncStorageWrapper(AsyncStorage), maxSize: 2097152 // 2MB - Android AsyncStorage limit }); const client = new ApolloClient({ uri: 'https://api.example.com/graphql', cache }); ``` ### Notes - AsyncStorage doesn't support values over 2MB on Android. For larger caches, consider MMKVStorageWrapper or MMKVWrapper. ``` -------------------------------- ### React Native Background Cache Persistence Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Configures Apollo Client cache persistence for React Native, specifically triggering persistence when the application moves to the background. This optimizes battery and performance by avoiding persistence during active use. It utilizes `AsyncStorageWrapper` and the 'background' trigger. Dependencies include React Native, @react-native-async-storage/async-storage, Apollo Client, and apollo3-cache-persist. ```javascript import AsyncStorage from '@react-native-async-storage/async-storage'; import { InMemoryCache } from '@apollo/client/core'; import { CachePersistor, AsyncStorageWrapper } from 'apollo3-cache-persist'; import { ApolloClient } from '@apollo/client'; const cache = new InMemoryCache(); // Persist only when app goes to background const persistor = new CachePersistor({ cache, storage: new AsyncStorageWrapper(AsyncStorage), trigger: 'background', // React Native only maxSize: 2097152 // 2MB }); await persistor.restore(); const client = new ApolloClient({ uri: 'https://api.example.com/graphql', cache }); // Cache persists when user switches apps or locks screen // No persistence during active use - better performance ``` -------------------------------- ### Persist Cache Configuration Options Source: https://github.com/apollographql/apollo-cache-persist/blob/master/docs/advanced-usage.md Defines the configuration options available when using the `persistCache` function or the `CachePersistor` constructor. These options control aspects like cache reference, storage provider, persistence triggers, debouncing, storage keys, serialization, maximum cache size, and debugging. ```typescript persistCache({ /** * Required options. */ // Reference to your Apollo cache. cache: ApolloCache, // Reference to your storage provider wrapped in a storage wrapper implementing PersistentStorage interface. storage: PersistentStorage, /** * Trigger options. */ // When to persist the cache. // // 'write': Persist upon every write to the cache. Default. // 'background': Persist when your app moves to the background. React Native only. // // For a custom trigger, provide a function. See below for more information. // To disable automatic persistence and manage persistence manually, provide false. trigger?: 'write' | 'background' | function | false, // Debounce interval between persists (in ms). // Defaults to 0 for 'background' and 1000 for 'write' and custom triggers. debounce?: number, /** * Storage options. */ // Key to use with the storage provider. Defaults to 'apollo-cache-persist'. key?: string, // Whether to serialize to JSON before/after persisting. Defaults to true. serialize?: boolean, // Maximum size of cache to persist (in bytes). // Defaults to 1048576 (1 MB). For unlimited cache size, provide false. // If exceeded, persistence will pause and app will start up cold on next launch. maxSize?: number | false, /** * Debugging options. */ // Enable console logging. debug?: boolean, }): Promise; ``` -------------------------------- ### Custom Cache Persistence Trigger Function Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Define custom logic for when cache persistence should occur by providing a trigger function. This allows for fine-grained control over persistence intervals or conditions. ```javascript import { InMemoryCache } from '@apollo/client/core'; import { CachePersistor, LocalStorageWrapper } from 'apollo3-cache-persist'; const cache = new InMemoryCache(); // Custom trigger: persist every 30 seconds const customTrigger = (persist) => { const intervalId = setInterval(() => { console.log('Custom trigger: persisting cache'); persist(); }, 30000); // Return cleanup function return () => clearInterval(intervalId); }; const persistor = new CachePersistor({ cache, storage: new LocalStorageWrapper(window.localStorage), trigger: customTrigger, debounce: 0 // No debounce for custom triggers }); await persistor.restore(); ``` -------------------------------- ### Persist Cache in React Native Source: https://github.com/apollographql/apollo-cache-persist/blob/master/README.md Demonstrates how to persist the Apollo Client cache in a React Native application using AsyncStorage. It's crucial to await the persistCache operation before initializing Apollo Client to ensure data is restored. ```javascript import AsyncStorage from '@react-native-async-storage/async-storage'; import { InMemoryCache } from '@apollo/client/core'; import { persistCache, AsyncStorageWrapper } from 'apollo3-cache-persist'; const cache = new InMemoryCache({...}); // await before instantiating ApolloClient, else queries might run before the cache is persisted await persistCache({ cache, storage: new AsyncStorageWrapper(AsyncStorage), }); // Continue setting up Apollo as usual. const client = new ApolloClient({ cache, ... }); ``` -------------------------------- ### Reset Cache on Schema Change with Apollo Cache Persist Source: https://github.com/apollographql/apollo-cache-persist/blob/master/docs/faq.md This JavaScript code demonstrates how to handle breaking schema changes by conditionally restoring or purging the Apollo Client cache using `CachePersistor`. It tracks schema versions to ensure data integrity. Dependencies include `@react-native-community/async-storage`, `@apollo/client/core`, and `apollo3-cache-persist`. ```javascript import AsyncStorage from '@react-native-community/async-storage'; import { InMemoryCache } from '@apollo/client/core'; import { CachePersistor, AsyncStorageWrapper } from 'apollo3-cache-persist'; const SCHEMA_VERSION = '3'; // Must be a string. const SCHEMA_VERSION_KEY = 'apollo-schema-version'; async function setupApollo() { const cache = new InMemoryCache({...}); const persistor = new CachePersistor({ cache, storage: new AsyncStorageWrapper(AsyncStorage), }); // Read the current schema version from AsyncStorage. const currentVersion = await AsyncStorage.getItem(SCHEMA_VERSION_KEY); if (currentVersion === SCHEMA_VERSION) { // If the current version matches the latest version, // we're good to go and can restore the cache. await persistor.restore(); } else { // Otherwise, we'll want to purge the outdated persisted cache // and mark ourselves as having updated to the latest version. await persistor.purge(); await AsyncStorage.setItem(SCHEMA_VERSION_KEY, SCHEMA_VERSION); } // Continue setting up Apollo as usual. } ``` -------------------------------- ### CachePersistor - Advanced Manual Control Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Provides full programmatic control over cache persistence operations. This class allows for manual control over persisting, restoring, purging, and managing persistence triggers. ```APIDOC ## CachePersistor - Advanced Manual Control ### Description Provides full programmatic control over cache persistence operations with methods for manual persist, restore, purge, and trigger management. ### Method `new CachePersistor(options)` ### Parameters #### Request Body - **cache** (InMemoryCache) - Required - The Apollo Client cache instance. - **storage** (StorageWrapper) - Required - An instance of a storage wrapper (e.g., `LocalStorageWrapper`, `AsyncStorageWrapper`). - **trigger** (string | Function) - Optional - Determines when the cache is persisted. Can be 'write' (on every write), 'background' (periodically in the background), `false` (manual only), or a custom function. Defaults to 'write'. - **debug** (boolean) - Optional - Enables console logging for debugging purposes. Defaults to false. ### Methods - **restore()**: Promise - Manually restores the cache from storage. - **persist()**: Promise - Forces an immediate persistence of the current cache state. - **purge()**: Promise - Clears all persisted cache data from storage. - **pause()**: void - Stops automatic cache persistence. - **resume()**: void - Resumes automatic cache persistence. - **remove()**: Promise - Permanently disables automatic persistence and clears persisted data. - **getLogs(print?: boolean)**: Array | void - Retrieves the log array, or prints them to the console if `print` is true. - **getSize()**: Promise - Returns the current size of the persisted cache in bytes. ### Request Example ```javascript import { InMemoryCache } from '@apollo/client/core'; import { CachePersistor, LocalStorageWrapper } from 'apollo3-cache-persist'; import { ApolloClient } from '@apollo/client'; const cache = new InMemoryCache(); const persistor = new CachePersistor({ cache, storage: new LocalStorageWrapper(window.localStorage), trigger: 'write', debug: true }); await persistor.restore(); const client = new ApolloClient({ uri: 'https://api.example.com/graphql', cache }); await persistor.persist(); await persistor.purge(); persistor.pause(); persistor.resume(); persistor.remove(); const logs = persistor.getLogs(); persistor.getLogs(true); const sizeInBytes = await persistor.getSize(); ``` ### Response - **restore()**: Promise - **persist()**: Promise - **purge()**: Promise - **remove()**: Promise - **getSize()**: Promise - The size of the persisted cache in bytes. ``` -------------------------------- ### Persist Apollo Cache with localStorage (JavaScript) Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Persists and restores Apollo cache using localStorage. It takes configuration options like cache, storage, debounce, maxSize, key, and debug. The function returns a promise that resolves when the cache is restored. ```javascript import { InMemoryCache } from '@apollo/client/core'; import { persistCache, LocalStorageWrapper } from 'apollo3-cache-persist'; import { ApolloClient } from '@apollo/client'; // Create cache instance const cache = new InMemoryCache(); // Persist cache with localStorage await persistCache({ cache, storage: new LocalStorageWrapper(window.localStorage), debounce: 1000, // Wait 1 second after last write before persisting maxSize: 1048576, // 1MB limit (default) key: 'apollo-cache-persist', // Storage key (default) debug: true // Enable console logging }); // Create Apollo Client after cache is restored const client = new ApolloClient({ uri: 'https://api.example.com/graphql', cache }); // Cache will now automatically persist on every write // and restore on next application launch ``` -------------------------------- ### Session Storage Cache Persistence with SessionStorageWrapper Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Wraps browser sessionStorage for temporary cache persistence that clears when the browser tab closes. This is useful for caching data that should not persist across sessions. ```javascript import { InMemoryCache } from '@apollo/client/core'; import { persistCache, SessionStorageWrapper } from 'apollo3-cache-persist'; const cache = new InMemoryCache(); // Cache persists only during browser session await persistCache({ cache, storage: new SessionStorageWrapper(window.sessionStorage), maxSize: false // Disable size limit }); // Cache data will be cleared when tab/window is closed ``` -------------------------------- ### Persist Apollo Cache with AsyncStorage (React Native) (JavaScript) Source: https://context7.com/apollographql/apollo-cache-persist/llms.txt Wraps React Native's AsyncStorage for Apollo cache persistence. It supports promise-based async operations and is configured with cache, storage, and maxSize. Note the Android AsyncStorage limit for values over 2MB. ```javascript import AsyncStorage from '@react-native-async-storage/async-storage'; import { InMemoryCache } from '@apollo/client/core'; import { persistCache, AsyncStorageWrapper } from 'apollo3-cache-persist'; import { ApolloClient } from '@apollo/client'; const cache = new InMemoryCache(); // Use AsyncStorage wrapper for React Native await persistCache({ cache, storage: new AsyncStorageWrapper(AsyncStorage), maxSize: 2097152 // 2MB - Android AsyncStorage limit }); const client = new ApolloClient({ uri: 'https://api.example.com/graphql', cache }); // Note: AsyncStorage doesn't support values over 2MB on Android // For larger caches, use MMKVStorageWrapper or MMKVWrapper instead ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.