Infinite Key Serialization

Purpose

Infinite Key Serialization addresses a fundamental challenge in infinite loading: uniquely and consistently identifying each paginated data request to enable reliable caching and revalidation. When fetching data page-by-page, each page's request key must be serialized into a stable string format that the SWR cache can recognize and differentiate. This serialization ensures that cached data for each page is properly stored, retrieved, and updated without collisions or inconsistencies.

Without such serialization utilities, keys representing infinite pages might be ambiguous or incompatible with the cache’s string-keyed storage, leading to stale data or unnecessary re-fetches. Thus, Infinite Key Serialization guarantees cache consistency and correctness across the infinite loading lifecycle.

Functionality

The core functionality revolves around transforming the dynamic page-based keys generated by an infinite loading key loader into stable, serializable strings:

Key Methods

Code Snippet

export const getFirstPageKey = (getKey: SWRInfiniteKeyLoader) => {
  return serialize(getKey ? getKey(0, null) : null)[0]
}

export const unstable_serialize = (getKey: SWRInfiniteKeyLoader) => {
  return INFINITE_PREFIX + getFirstPageKey(getKey)
}

Here, serialize is a utility that converts the key (which may be complex) into a string tuple, ensuring uniqueness and cache compatibility.

Integration

Infinite Key Serialization serves as a foundational utility within the Infinite Loading Support parent topic. While the parent topic manages the overall workflow of paginated data fetching, page size management, and data concatenation, this subtopic focuses exclusively on how each page's request key is uniquely identified and stored.

In sum, Infinite Key Serialization is the glue that binds the dynamic nature of infinite page keys to the stable, string-based cache infrastructure, enabling all other infinite loading features to function reliably.

Diagram

flowchart TD
  A[Infinite Key Loader Function] --> B[Generate Page Key (e.g. page 0,1,...)]
  B --> C[Serialize Key to String]
  C --> D{Is First Page?}
  D -->|Yes| E[Extract First Page Key]
  E --> F[Prefix with INFINITE_PREFIX]
  D -->|No| G[Use Serialized Key as-is]
  F & G --> H[Store/Retrieve in SWR Cache]
  H --> I[Enable Infinite Loading Hook & Middleware]

This flowchart illustrates how infinite page keys are generated, serialized, optionally prefixed, and then used by the SWR cache to support infinite loading workflows.