serialize.ts
Overview
The serialize.ts file provides essential utility functions related to key serialization for infinite loading in the SWR (stale-while-revalidate) data fetching ecosystem. Specifically, it focuses on generating and serializing the cache keys for paginated or infinite data requests in a consistent, stable, and unique manner.
Infinite loading relies on dynamically generated keys for each page of data fetched. This file:
Extracts the serialized key for the first page of an infinite data set.
Constructs a unique infinite cache key by prefixing the serialized first page key.
Facilitates proper cache management by ensuring keys used for infinite loading are stable and distinguishable from normal keys.
These utilities are foundational for the infinite loading middleware and hooks (e.g., useSWRInfinite), enabling them to properly identify and manage paginated data caches.
Exports
getFirstPageKey
export const getFirstPageKey = (getKey: SWRInfiniteKeyLoader) => string
Description
Generates the serialized cache key for the first page (pageIndex = 0) of an infinite data request, using the provided infinite key loader function.
Calls the
getKeyloader function with parameters(0, null)to get the first page key.Uses the generic
serializeutility to convert the possibly complex key into a stable string tuple.Returns the first element of the serialized key tuple, which is a string representation suitable for cache indexing.
Parameters
Name | Type | Description |
|---|---|---|
getKey |
| A function that returns the key for a given page index and previous page data. |
Returns
string— The serialized string key representing the first page's cache key.
Usage Example
import { getFirstPageKey } from './serialize'
import type { SWRInfiniteKeyLoader } from './types'
const keyLoader: SWRInfiniteKeyLoader = (index, previousPageData) => {
if (index === 0) return ['api/items', { limit: 10 }]
if (previousPageData && previousPageData.nextCursor)
return ['api/items', { cursor: previousPageData.nextCursor }]
return null
}
const firstPageKey = getFirstPageKey(keyLoader)
console.log(firstPageKey) // e.g. "api/items?limit=10"
unstable_serialize
export const unstable_serialize = (getKey: SWRInfiniteKeyLoader) => string
Description
Generates a unique serialized cache key string for the entire infinite loading data source by prefixing the serialized first page key with a constant string INFINITE_PREFIX.
This function is primarily for internal or experimental use (as suggested by the unstable_ prefix). It helps differentiate infinite loading keys from normal keys in the global SWR cache, preventing collisions and allowing middleware layers to recognize infinite loading entries.
Parameters
Name | Type | Description |
|---|---|---|
getKey |
| The infinite key loader function to generate keys from. |
Returns
string— The serialized infinite key string prefixed withINFINITE_PREFIX.
Usage Example
import { unstable_serialize } from './serialize'
import type { SWRInfiniteKeyLoader } from './types'
const keyLoader: SWRInfiniteKeyLoader = (index, prev) => ['api/items', index]
const infiniteKey = unstable_serialize(keyLoader)
console.log(infiniteKey) // e.g. "__INFINITE__api/items?index=0"
Implementation Details
The file imports
serializefrom an internal utility module. Thisserializefunction converts complex keys (arrays, objects) into stable string tuples that can be used as cache keys in SWR.INFINITE_PREFIXis a constant string imported from internal constants, typically something like"INFINITE".The
getFirstPageKeycallsgetKeywith(0, null)— representing the first page index and no previous page data, as the first page typically does not depend on any previous data.The serialized first page key (string) is then used as the base for infinite caching.
The
unstable_serializefunction prefixes the first page key withINFINITE_PREFIXto create a unique identifier for the infinite loading instance, which is critical for storing metadata such as page size and state in the global cache.
Relationships and Interactions
With Infinite Loading Middleware and Hooks:
This file provides key serialization utilities used by the infinite loading middleware and hooks likeuseSWRInfinite. These hooks need to generate stable cache keys for each page and for the overall infinite data set.With Global Cache:
The serialized keys generated here are used as keys in the SWR global cache to store and retrieve page data and pagination metadata (e.g., current page size).With Serialization Utilities:
Relies on a genericserializeutility that handles converting complex keys to stable strings, ensuring keys are comparable and cache-friendly.With Infinite Loading Constants:
UsesINFINITE_PREFIXto namespace infinite keys, preventing collisions with normal keys and allowing middleware and tooling to distinguish infinite loading entries.
Mermaid Diagram
flowchart TD
A[Infinite Key Loader Function (getKey)] --> B[Generate Page Key for Page 0]
B --> C[Serialize Key to String Tuple]
C --> D[Extract Serialized First Page Key (string)]
D --> E{Build Infinite Key?}
E -->|Yes| F[Prefix with INFINITE_PREFIX]
E -->|No| G[Return Serialized Key As-Is]
F & G --> H[Use as Cache Key in SWR Global Cache]
H --> I[Support Infinite Loading Hook & Middleware]
Summary
The serialize.ts file encapsulates the logic to:
Obtain a stable serialized string key for the first page of infinite paginated data.
Construct a unique infinite loading cache key by prefixing the first page key.
Provide these keys as identifiers for SWR's infinite loading mechanisms to store and manage page data and pagination state effectively.
This simple but critical utility ensures cache consistency and uniqueness, enabling the infinite loading features to function correctly across the application.
Appendix: Types and Constants (Context)
SWRInfiniteKeyLoader:
A type describing a function(pageIndex: number, previousPageData: any) => Key | null, whereKeycan be a string, array, or null, representing the resource key for each page.serialize:
Utility converting complex keys into stable serialized string tuples.INFINITE_PREFIX:
A string constant (e.g.,"INFINITE") used to prefix keys related to infinite loading.