cache.ts


Overview

The cache.ts file is a core utility module responsible for initializing and managing cache providers within the SWR (stale-while-revalidate) data fetching ecosystem. It orchestrates the creation and lifecycle of global state associated with a cache provider, including:

This module enables efficient coordination between multiple components sharing the same cache provider, allowing them to reactively update when cached data changes or when revalidation events occur.


Detailed Explanation

Key Concepts


Functions and Exports

revalidateAllKeys

const revalidateAllKeys = (
  revalidators: Record<string, RevalidateCallback[]>,
  type: RevalidateEvent
) => { ... }

initCache

export const initCache = <Data = any>(
  provider: Cache<Data>,
  options?: Partial<ProviderConfiguration>
):
  | [Cache<Data>, ScopedMutator, () => void, () => void]
  | [Cache<Data>, ScopedMutator]
  | undefined => { ... }

Internal Implementation Details


Usage Example

import { initCache } from './cache'

// Assume `myCache` is a Map or compatible cache provider.
const myCache = new Map<string, any>()

// Initialize the cache provider
const [provider, mutate, initProvider, unmount] = initCache(myCache, {
  // Optional config overrides
  initFocus: (callback) => {
    window.addEventListener('focus', callback)
    return () => window.removeEventListener('focus', callback)
  },
  initReconnect: (callback) => {
    window.addEventListener('online', callback)
    return () => window.removeEventListener('online', callback)
  }
})!

// Subscribe to changes of a key
const unsubscribe = (SWRGlobalState.get(provider) as any)[6]('some-key', (current, prev) => {
  console.log('Cache value changed:', prev, '->', current)
})

// Mutate cache entry and trigger revalidation
mutate('some-key', async () => {
  const data = await fetchData()
  return data
})

// Later, cleanup event listeners on unmount
unmount()

How This File Interacts with the System


Mermaid Class Diagram

classDiagram
    class CacheProvider {
        <<interface>>
        +get(key: string): any
        +set(key: string, value: any): void
        +delete(key: string): void
    }

    class CacheState {
        -EVENT_REVALIDATORS: Record<string, RevalidateCallback[]>
        -subscriptions: Record<string, ((current: any, prev: any) => void)[]>
        -mutate: ScopedMutator
        -setter(key: string, value: any, prev: any): void
        -subscribe(key: string, callback: (current: any, prev: any) => void): () => void
        -unmount(): void
        -initProvider(): void
    }

    class CacheInitializer {
        +initCache(provider: CacheProvider, options?): [CacheProvider, ScopedMutator, () => void, () => void] | [CacheProvider, ScopedMutator] | undefined
    }

    CacheInitializer --> CacheState : creates/manages
    CacheState *-- CacheProvider : uses

Summary

The cache.ts module is a foundational piece in the SWR architecture, responsible for:

By abstracting these concerns, the module enables efficient, reactive, and event-driven cache management that supports the stale-while-revalidate strategy of the broader SWR data fetching system.