This document explains how to use persistent cache with the @pubflow/react package.
- Overview
- Setup
- Configuration Options
- Usage with useBridgeCrud
- Usage with useBridgeQuery
- Advanced Usage
By default, SWR (the data fetching library used by Pubflow) stores its cache in memory. This means that when the user refreshes the page or closes and reopens the application, all cached data is lost and must be fetched again.
Persistent cache solves this problem by storing the cache in localStorage (or AsyncStorage for React Native), allowing the data to persist between page refreshes and application restarts. This provides several benefits:
- Improved initial load time: The application can show cached data immediately while fetching fresh data in the background.
- Reduced API calls: The application doesn't need to refetch data that hasn't changed.
- Better offline experience: The application can show cached data even when offline.
To enable persistent cache, you need to:
- Create a persistent cache provider
- Pass it to the
PubflowProvider
// App.jsx
import React from 'react';
import { PubflowProvider, createPersistentCache } from '@pubflow/react';
function App() {
// Create a persistent cache provider
const persistentCacheProvider = createPersistentCache({
prefix: 'my_app_cache',
ttl: 24 * 60 * 60 * 1000, // 24 hours
debug: process.env.NODE_ENV === 'development'
});
return (
<PubflowProvider
config={{
baseUrl: 'https://api.example.com',
bridgeBasePath: '/bridge',
authBasePath: '/auth'
}}
persistentCache={{
enabled: true,
provider: persistentCacheProvider
}}
>
<YourApp />
</PubflowProvider>
);
}
export default App;// _app.js
import { PubflowProvider, createPersistentCache } from '@pubflow/nextjs';
function MyApp({ Component, pageProps }) {
// Create a persistent cache provider
const persistentCacheProvider = createPersistentCache({
prefix: 'my_nextjs_app_cache',
ttl: 24 * 60 * 60 * 1000, // 24 hours
debug: process.env.NODE_ENV === 'development'
});
return (
<PubflowProvider
config={{
baseUrl: 'https://api.example.com',
bridgeBasePath: '/bridge',
authBasePath: '/auth'
}}
persistentCache={{
enabled: true,
provider: persistentCacheProvider
}}
>
<Component {...pageProps} />
</PubflowProvider>
);
}
export default MyApp;// App.js
import React from 'react';
import { PubflowProvider, createPersistentCache } from '@pubflow/react-native';
function App() {
// Create a persistent cache provider
const persistentCacheProvider = createPersistentCache({
prefix: 'my_rn_app_cache',
ttl: 24 * 60 * 60 * 1000, // 24 hours
debug: __DEV__
});
return (
<PubflowProvider
config={{
baseUrl: 'https://api.example.com',
bridgeBasePath: '/bridge',
authBasePath: '/auth'
}}
persistentCache={{
enabled: true,
provider: persistentCacheProvider
}}
>
<YourApp />
</PubflowProvider>
);
}
export default App;The createPersistentCache function accepts the following options:
| Option | Type | Description | Default |
|---|---|---|---|
| prefix | string | Prefix for storage keys | 'pubflow_cache' |
| ttl | number | Time to live in milliseconds | 24 * 60 * 60 * 1000 (24 hours) |
| maxItemSize | number | Maximum size of a cache item in bytes | 2 * 1024 * 1024 (2MB) |
| compress | boolean | Whether to compress cache data to save space | false |
| serialize | function | Custom serialization function | JSON.stringify |
| deserialize | function | Custom deserialization function | JSON.parse |
| debug | boolean | Whether to log cache operations | false |
| storage | string | Storage mechanism to use (React only) | 'localStorage' |
Once you've set up persistent cache, it will automatically work with useBridgeCrud. The cache keys are generated based on the entity configuration and search parameters, ensuring that the cache is properly maintained.
import { useBridgeCrud } from '@pubflow/react';
function UserList() {
const {
items: users,
loading,
error,
page,
setPage,
limit,
setLimit,
totalItems,
hasMore
} = useBridgeCrud({
entityConfig: {
endpoint: 'users'
}
});
// The data will be cached and persisted between page refreshes
return (
<div>
{/* Your UI */}
</div>
);
}Similarly, useBridgeQuery will automatically use the persistent cache:
import { useBridgeApi, useBridgeQuery } from '@pubflow/react';
function UserList() {
const userService = useBridgeApi({ endpoint: 'users' });
const {
data: users,
isLoading,
error,
refetch
} = useBridgeQuery(
userService,
'list',
{ limit: 10, page: 1 }
);
// The data will be cached and persisted between page refreshes
return (
<div>
{/* Your UI */}
</div>
);
}By default, the cache keys are generated based on the entity configuration and search parameters. However, you can customize the prefix to avoid conflicts with other applications:
const persistentCacheProvider = createPersistentCache({
prefix: 'my_custom_app_cache'
});For large datasets, you can enable compression to reduce the storage size:
const persistentCacheProvider = createPersistentCache({
compress: true
});The cache is automatically invalidated when:
- The TTL (time to live) expires
- A mutation operation is performed (create, update, delete)
You can also manually invalidate the cache by calling the clear method on the SWR cache:
import { useSWRConfig } from 'swr';
function ClearCacheButton() {
const { cache } = useSWRConfig();
const handleClearCache = () => {
cache.clear();
};
return (
<button onClick={handleClearCache}>
Clear Cache
</button>
);
}You can enable debug mode to see cache operations in the console:
const persistentCacheProvider = createPersistentCache({
debug: process.env.NODE_ENV === 'development'
});This will log cache hits, misses, and other operations, which can be useful for debugging.