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
EMPTY_CACHE:
An empty object{}used as a fallback cache value when no cached data exists.INITIAL_CACHE:
A record (Record<string, any>) storing the initial cached values before any client-side updates occur, allowing retrieval of the original server-side cache snapshot.STR_UNDEFINED:
String literal"undefined"used to compare against the type of global variables for environment detection.
Environment and Feature Detection Utilities
These exports help the library adapt behavior depending on the runtime environment.
isWindowDefined: boolean
Description:
Boolean flag indicating whether the globalwindowobject is defined. Useful to detect browser environment.Implementation:
Checkstypeof window != 'undefined'.Usage Example:
if (isWindowDefined) { // Safe to access window-specific APIs }
isDocumentDefined: boolean
Description:
Boolean flag indicating whether the globaldocumentobject is defined.Implementation:
Checkstypeof document != 'undefined'.
isLegacyDeno: boolean
Description:
Boolean flag detecting legacy Deno environment inside a browser-likewindowobject.Implementation:
trueifwindowexists and has aDenoproperty (legacy Deno embedding).
hasRequestAnimationFrame(): boolean
Description:
Function that returnstrueif therequestAnimationFrameAPI is available in the current environment.Implementation:
Returnstrueifwindowis defined andwindow.requestAnimationFrameis defined.Usage Example:
if (hasRequestAnimationFrame()) { window.requestAnimationFrame(() => { // animation logic }); }
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
cache: Cache
The cache instance to operate on. This is a map-like object that stores key-value pairs for cached data.key: string | undefined
The cache key to target. Ifundefined, getters and setters default to empty cache behavior.
Returns
A tuple of four functions typed as readonly (immutable array):
Getter:
() => T
Returns the cached value forkeyfromcacheor an empty cache if not found or key undefined.Setter:
(info: T) => void
Updates the cached value forkeyby merging the previous value withinfo. Also updatesINITIAL_CACHEif this is the first client-side update to preserve the original.Subscriber:
(callback) => void(fromstate[6])
Returns the subscription method for cache changes, allowing listeners to react on updates.Server Snapshot Getter:
() => T
Returns the initial cached value fromINITIAL_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
Uses
SWRGlobalState.get(cache)to retrieve the global state tuple associated with the cache.Before updating cache via setter, stores the previous value in
INITIAL_CACHEif not already stored. This ensures original server-side cache values are preserved even after client-side mutations.The setter merges the previous cache value and the provided
infousing amergeObjectsutility, allowing partial updates.The subscriber method is directly taken from the global state (
state[6]), enabling reactive cache subscriptions.
Interaction with Other Parts of the System
Types imported:
Cache,State, andGlobalStatetypes define the shape of cache and state objects.SWRGlobalState (imported from './global-state'):
Provides access to global caching state, including methods for updating and subscribing.Shared utilities (from './shared'):
IncludesisUndefined(to check undefined values) andmergeObjects(to merge two objects).Cache system:
The helper directly interacts with the cache instance, which is a key-value store used throughout the SWR library for caching fetched data.
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.