### Install swr-idb-cache using npm
Source: https://github.com/piotr-cz/swr-idb-cache/blob/main/README.md
Installs the swr-idb-cache package and its dependencies using npm. This command is used to add the library to your project's package.json file.
```console
npm install --save @piotr-cz/swr-idb-cache
```
--------------------------------
### Install swr-idb-cache using Yarn
Source: https://github.com/piotr-cz/swr-idb-cache/blob/main/README.md
Installs the swr-idb-cache package and its dependencies using Yarn. This command is used to add the library to your project's yarn.lock file and package.json.
```console
yarn add @piotr-cz/swr-idb-cache
```
--------------------------------
### Mock IndexedDB in Tests (Shell)
Source: https://github.com/piotr-cz/swr-idb-cache/blob/main/README.md
Installs the 'fake-indexeddb' package as a development dependency, which can be used to mock IndexedDB in test environments.
```shell
npm install --save-dev fake-indexeddb
```
--------------------------------
### Mock IndexedDB in Tests (TypeScript)
Source: https://github.com/piotr-cz/swr-idb-cache/blob/main/README.md
Imports 'fake-indexeddb/auto' to automatically mock IndexedDB for tests. This setup is typically placed in a test setup file.
```typescript
// src/setupTests.ts
import 'fake-indexeddb/auto'
```
--------------------------------
### Cache Manipulation with SWR's useSWRConfig
Source: https://context7.com/piotr-cz/swr-idb-cache/llms.txt
Directly manage the SWR cache using the `useSWRConfig` hook. This allows for operations like deleting individual cache entries, clearing the entire cache (both in-memory and IndexedDB), and triggering data revalidation. The cache provider exposes `get`, `set`, `delete`, `keys`, and `clear` methods.
```jsx
import useSWR, { useSWRConfig } from 'swr'
function UserProfile() {
const { data, mutate } = useSWR('/api/user/123', fetcher)
const { cache } = useSWRConfig()
const handleDelete = async () => {
// Delete from backend
await fetch('/api/user/123', { method: 'DELETE' })
// Remove from SWR cache (also removes from IndexedDB)
cache.delete('/api/user/123')
}
const handleClearAll = () => {
// Clear entire cache (both in-memory and IndexedDB)
cache.clear()
}
const handleRefresh = () => {
// Revalidate - fetches fresh data and updates cache
mutate()
}
return (
{data?.name}
)
}
```
--------------------------------
### Ignore API Endpoints from Cache Persistence (JavaScript)
Source: https://github.com/piotr-cz/swr-idb-cache/blob/main/README.md
Creates a custom storage handler that extends the timestamp storage handler to ignore specific API endpoints. Entries with keys starting with '/api/device/' are not stored. This handler is then passed to the SWRConfig.
```javascript
// custom-storage-handler.js
import { timestampStorageHandler } from '@piotr-cz/swr-idb-cache'
const blacklistStorageHandler = {
...timestampStorageHandler,
// Ignore entries fetched from API endpoints starting with /api/device
replace: (key, value) =>
!key.startsWith('/api/device/')
// Wrapped value
? timestampStorageHandler.replace(key, value)
// Undefined to ignore storing value
: undefined,
}
export default blacklistStorageHandler
```
--------------------------------
### Custom Storage Handler with Garbage Collection (TypeScript)
Source: https://context7.com/piotr-cz/swr-idb-cache/llms.txt
A custom storage handler can be created by extending `timestampStorageHandler` to implement cache expiration logic. The `revive` method can return `undefined` for stale entries, effectively removing them from the cache during retrieval. This example demonstrates a 7-day expiration policy.
```typescript
import { timestampStorageHandler, type StorageHandler } from '@piotr-cz/swr-idb-cache'
// Define max age of 7 days in milliseconds
const maxAge = 7 * 24 * 60 * 60 * 1000
const gcStorageHandler: StorageHandler = {
...timestampStorageHandler,
revive: (key, storeObject) => {
// Return undefined for expired entries (removes from cache)
if (storeObject.ts <= Date.now() - maxAge) {
return undefined
}
// Return unwrapped value for valid entries
return timestampStorageHandler.revive(key, storeObject)
},
}
// Usage
const cacheProvider = await createCacheProvider({
dbName: 'my-app',
storeName: 'cache',
storageHandler: gcStorageHandler,
})
```
--------------------------------
### Initialize SWR with IndexedDB Cache Provider using react-use-promise
Source: https://github.com/piotr-cz/swr-idb-cache/blob/main/README.md
Shows an alternative method for initializing the IndexedDB cache provider using the `react-use-promise` library. This approach leverages promises for asynchronous initialization and integration with SWR.
```js
import createCacheProvider from '@piotr-cz/swr-idb-cache'
import usePromise from 'react-use-promise'
function App() {
// Initialize
const [ cacheProvider ] = usePromise(() => createCacheProvider({
dbName: 'my-app',
storeName: 'swr-cache',
}), [])
// …
}
```
--------------------------------
### Initialize SWR with IndexedDB Cache Provider using useCacheProvider hook
Source: https://github.com/piotr-cz/swr-idb-cache/blob/main/README.md
Demonstrates how to initialize the IndexedDB cache provider using the `useCacheProvider` hook and integrate it with SWR's `SWRConfig`. It includes a fallback component rendering while the cache provider is initializing asynchronously.
```jsx
// App.jsx
import { SWRConfig } from 'swr'
import { useCacheProvider } from '@piotr-cz/swr-idb-cache'
function App() {
// Initialize
const cacheProvider = useCacheProvider({
dbName: 'my-app',
storeName: 'swr-cache',
})
// Cache Provider is being initialized - render fallback component in the meantime
if (!cacheProvider) {
return
Initializing cache…
}
return (
)
}
```
--------------------------------
### Create IndexedDB Cache Provider for SWR (TypeScript)
Source: https://context7.com/piotr-cz/swr-idb-cache/llms.txt
The `createCacheProvider` function creates an IndexedDB-backed cache provider for SWR. It returns a Promise that resolves to a cache provider function compatible with SWR's `provider` configuration option. Initialization requires rendering a fallback component until the provider is ready.
```typescript
import createCacheProvider from '@piotr-cz/swr-idb-cache'
import { SWRConfig } from 'swr'
import usePromise from 'react-use-promise'
function App() {
const [cacheProvider, error, state] = usePromise(
() => createCacheProvider({
dbName: 'my-app',
storeName: 'swr-cache',
version: 1,
onError: (err) => console.error('IndexedDB error:', err),
}),
[]
)
if (state === 'pending') {
return
Loading cache...
}
if (error) {
return
Failed to initialize cache
}
return (
)
}
```
--------------------------------
### Testing SWR IndexedDB Cache with Mocking
Source: https://context7.com/piotr-cz/swr-idb-cache/llms.txt
Facilitate testing of applications using SWR IndexedDB cache by employing mocking strategies. Option 1 uses `fake-indexeddb` to simulate IndexedDB in Node.js environments. Option 2 uses Vitest to mock the cache provider, replacing the IndexedDB implementation with an in-memory Map for isolated unit tests.
```typescript
// Option 1: Use fake-indexeddb
// Install: npm install --save-dev fake-indexeddb
// src/setupTests.ts
import 'fake-indexeddb/auto'
```
```typescript
// Option 2: Mock the cache provider with Vitest
// src/App.test.tsx
import { describe, it, vi, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
type SWRIdbCacheExports = typeof import('@piotr-cz/swr-idb-cache')
vi.mock('@piotr-cz/swr-idb-cache', async (importOriginal): Promise => {
const mod = await importOriginal()
return {
...mod,
useCacheProvider: () => () => new Map(), // Return in-memory Map instead
}
})
describe('App', () => {
it('renders with mocked cache provider', async () => {
render()
expect(await screen.findByText('Dashboard')).toBeInTheDocument()
})
})
```
--------------------------------
### Use Cache Provider Hook for SWR (JSX)
Source: https://context7.com/piotr-cz/swr-idb-cache/llms.txt
The `useCacheProvider` hook simplifies integrating `createCacheProvider` into React components. It returns `undefined` during initialization and the cache provider once ready, automatically handling cleanup on unmount. This allows for seamless SWR configuration with IndexedDB caching.
```jsx
import { SWRConfig } from 'swr'
import { useCacheProvider } from '@piotr-cz/swr-idb-cache'
function App() {
const cacheProvider = useCacheProvider({
dbName: 'my-app',
storeName: 'swr-cache',
})
// Render fallback while cache provider initializes
if (!cacheProvider) {
return
Initializing cache...
}
return (
)
}
function Dashboard() {
// useSWR calls now use IndexedDB-backed cache
const { data } = useSWR('/api/user', fetcher)
return
{data?.name}
}
```
--------------------------------
### Mock Cache Provider with Vitest (TypeScript)
Source: https://github.com/piotr-cz/swr-idb-cache/blob/main/README.md
Mocks the 'useCacheProvider' function from '@piotr-cz/swr-idb-cache' using Vitest. This mock returns a function that creates a new Map instance, effectively providing a simple in-memory cache for testing purposes.
```typescript
// src/App.test.tsx
type SWRIdbCacheExports = typeof import('@piotr-cz/swr-idb-cache')
vi.mock('@piotr-cz/swr-idb-cache', async (importOriginal): Promise => {
const mod = await importOriginal()
return {
...mod,
useCacheProvider: () => () => new Map(),
}
})
```
--------------------------------
### Default Simple Storage Handler for IndexedDB Cache (TypeScript)
Source: https://context7.com/piotr-cz/swr-idb-cache/llms.txt
The `simpleStorageHandler` is the default storage handler for `@piotr-cz/swr-idb-cache`. It stores values directly in IndexedDB without any transformation, making it suitable for basic caching needs where no additional metadata like timestamps is required.
```typescript
import createCacheProvider, { simpleStorageHandler } from '@piotr-cz/swr-idb-cache'
const cacheProvider = await createCacheProvider({
dbName: 'my-app',
storeName: 'cache',
storageHandler: simpleStorageHandler, // This is the default
})
// Values are stored as-is:
// Key: '/api/users'
// Value: { data: [...], isLoading: false, isValidating: false }
```
--------------------------------
### Implement Garbage Collector with Custom Storage Handler (JavaScript)
Source: https://github.com/piotr-cz/swr-idb-cache/blob/main/README.md
Defines a custom storage handler that extends the timestamp storage handler to implement garbage collection. Entries older than 7 days are considered stale and will not be revived. This handler is then passed to the SWRConfig.
```javascript
// custom-storage-handler.js
import { timestampStorageHandler } from '@piotr-cz/swr-idb-cache'
// Define max age of 7 days
const maxAge = 7 * 24 * 60 * 60 * 1e3
const gcStorageHandler = {
...timestampStorageHandler,
// Revive each entry only when it's timestamp is newer than expiration
revive: (key, storeObject) =>
storeObject.ts > Date.now() - maxAge
// Unwrapped value
? timestampStorageHandler.revive(key, storeObject)
// Undefined to indicate item is stale
: undefined,
}
export default gcStorageHandler
```
```javascript
// App.jsx
import { SWRConfig } from 'swr'
import { useCacheProvider } from '@piotr-cz/swr-idb-cache'
import customStorageHandler from './custom-storage-handler.js'
function App() {
// Initialize
const cacheProvider = useCacheProvider({
dbName: 'my-app',
storeName: 'swr-cache',
storageHandler: customStorageHandler,
})
// …
}
```
--------------------------------
### Custom Storage Handler with Blacklist for SWR IndexedDB Cache
Source: https://context7.com/piotr-cz/swr-idb-cache/llms.txt
Implement a custom storage handler to exclude specific API endpoints from IndexedDB persistence while maintaining in-memory caching. This is useful for sensitive or device-specific data. It extends the default `timestampStorageHandler` and overrides the `replace` method to conditionally skip IndexedDB storage.
```typescript
import { timestampStorageHandler, type StorageHandler } from '@piotr-cz/swr-idb-cache'
const blacklistStorageHandler: StorageHandler = {
...timestampStorageHandler,
replace: (key, value) => {
// Don't persist device-specific or sensitive endpoints
if (key.startsWith('/api/device/') || key.includes('/auth/')) {
return undefined // Skip IndexedDB storage
}
return timestampStorageHandler.replace(key, value)
},
}
// Usage
const cacheProvider = await createCacheProvider({
dbName: 'my-app',
storeName: 'cache',
storageHandler: blacklistStorageHandler,
})
```
--------------------------------
### Timestamp Storage Handler for IndexedDB Cache (TypeScript)
Source: https://context7.com/piotr-cz/swr-idb-cache/llms.txt
The `timestampStorageHandler` enhances caching by storing each value with a timestamp. This enables time-based cache invalidation and garbage collection. Cached data is stored as `{ value: Data, ts: number }` objects, with an indexed timestamp field for efficient querying.
```typescript
import createCacheProvider, { timestampStorageHandler } from '@piotr-cz/swr-idb-cache'
const cacheProvider = await createCacheProvider({
dbName: 'my-app',
storeName: 'cache',
storageHandler: timestampStorageHandler,
})
// Values are stored with timestamps:
// Key: '/api/users'
// Value: { value: { data: [...] }, ts: 1704067200000 }
```
--------------------------------
### Delete a cache entry using SWR's cache API
Source: https://github.com/piotr-cz/swr-idb-cache/blob/main/README.md
Illustrates how to delete a specific cache entry from SWR's cache using the `cache.delete()` method. This is useful for manually invalidating or removing data from the cache.
```jsx
import useSWR, { useSWRConfig } from 'swr'
export default function Item() {
const { data, error } = useSWR('/api/data')
const { cache } = useSWRConfig()
const handleRemove = () => {
// Remove from state
// …
// Remove from cache with key used in useSWR hook
cache.delete('/api/data')
}
return (
{/** Show item **}
{data &&
{data.label}
}
{/** Remove item **}
)
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.