helper.ts


Overview

The helper.ts file provides utility functions and helpers primarily focused on managing and interacting with cache state within a SWR (stale-while-revalidate) data-fetching context. It includes environment detection utilities (such as checking for window or document existence), feature detection (e.g., requestAnimationFrame), and a key function createCacheHelper that abstracts cache access, mutation, subscription, and snapshot retrieval.

This file plays a crucial role in the SWR global state management system by facilitating safe and consistent cache operations, while also accommodating different runtime environments (browser, Node.js, jsdom, legacy Deno).


Detailed Explanations

Constants


Environment and Feature Detection Utilities

These exports help the library adapt behavior depending on the runtime environment.

isWindowDefined: boolean

isDocumentDefined: boolean

isLegacyDeno: boolean

hasRequestAnimationFrame(): boolean


Main Function: createCacheHelper

export const createCacheHelper = <Data = any, T = State<Data, any>>(
  cache: Cache,
  key: string | undefined
) => { ... }

Purpose

Creates a tuple of four helper functions (getter, setter, subscriber, server snapshot getter) to interact with a cache for a specific key in the SWR global state.

This abstraction provides consistent cache access and mutation logic with built-in initialization tracking and merge strategy.


Parameters


Returns

A tuple of four functions typed as readonly (immutable array):

  1. Getter: () => T
    Returns the cached value for key from cache or an empty cache if not found or key undefined.

  2. Setter: (info: T) => void
    Updates the cached value for key by merging the previous value with info. Also updates INITIAL_CACHE if this is the first client-side update to preserve the original.

  3. Subscriber: (callback) => void (from state[6])
    Returns the subscription method for cache changes, allowing listeners to react on updates.

  4. Server Snapshot Getter: () => T
    Returns the initial cached value from INITIAL_CACHE (representing server-side snapshot) if available, otherwise returns current cached value.


Usage Example

const [getCache, setCache, subscribeCache, getServerSnapshot] = createCacheHelper<MyDataType>(cache, 'user-data')

// Get current cache
const currentData = getCache()

// Update cache
setCache({ name: 'Alice' })

// Subscribe to cache changes
subscribeCache((key, newValue) => {
  console.log(`${key} updated:`, newValue)
})

// Get server snapshot of cache
const snapshot = getServerSnapshot()

Implementation Details


Interaction with Other Parts of the System

This file is a utility layer that abstracts common cache operations, ensuring consistent behavior and integration with the SWR global state management system.


Visual Diagram

The following Mermaid flowchart shows the main functions returned by createCacheHelper and their relationships with the cache and global state.

flowchart TD
    A[Cache Instance] -->|get(key)| G[Getter Function]
    A -->|get(key)| SSG[Server Snapshot Getter]
    A -->|get(key) prev| M[Merge with info]
    M -->|set(key, merged)| A
    GSW[SWRGlobalState.get(cache)] -->|returns| GS[GlobalState Tuple]
    GS -->|state[5]: updateCache| M
    GS -->|state[6]: subscribe| SUB[Subscriber Function]

    subgraph createCacheHelper
        G
        M[Setter Function]
        SUB
        SSG
    end

Summary

helper.ts provides essential environment detection utilities and a powerful cache helper function to interact with SWR's global cache state safely and efficiently. The createCacheHelper function encapsulates cache get/set operations, subscription, and access to the original server cache snapshot. This utility supports the SWR cache lifecycle and ensures consistent cache data handling across different runtime environments.