index.ts


Overview

The index.ts file serves as the main aggregation and re-export module for a core data fetching library. Its primary purpose is to consolidate and expose various utilities, configuration contexts, constants, event handlers, and types related to the library’s stale-while-revalidate (SWR) data fetching strategy. It acts as the central access point for consumers of this module, enabling them to import key functionalities from a single location.

Additionally, index.ts performs essential initialization steps, such as setting up developer tools integration to enhance debugging and developer experience.


Detailed Explanation

Purpose and Role


Exported Entities

Exported Name

Source Path

Description

SWRConfig

./utils/config-context

React context provider for global SWR configuration.

revalidateEvents

./events

Collection of constants representing revalidation event types (e.g., focus, reconnect).

INFINITE_PREFIX

./constants

A string prefix constant used for identifying infinite loading keys (e.g., for infinite scroll).

initCache

./utils/cache

Function to initialize or retrieve a cache provider instance.

defaultConfig

./utils/config

Default configuration object for SWR behavior.

cache

./utils/config

The default cache provider instance.

mutate

./utils/config

Function to manually mutate cache data and trigger revalidation.

compare

./utils/config

Utility function for deep equality comparison (used internally for cache keys and data).

setupDevTools

./utils/devtools

Function to initialize developer tools integration (invoked immediately).

All exports from

./utils/env

Environment detection utilities (e.g., isBrowser, isServer).

SWRGlobalState

./utils/global-state

Singleton managing global SWR state, including event listeners and subscriptions.

stableHash

./utils/hash

Utility to compute stable hashes for keys to generate consistent cache keys.

All exports from

./utils/helper

Various helper functions used throughout the SWR implementation.

All exports from

./utils/shared

Shared utilities and constants.

mergeConfigs

./utils/merge-config

Utility to deep merge multiple SWR configuration objects.

internalMutate

./utils/mutate

Internal mutation function with extended capabilities for cache mutation.

normalize

./utils/normalize-args

Normalizes arguments passed to hooks or functions into a consistent format.

withArgs

./utils/resolve-args

Higher-order function to wrap handlers with argument resolution logic.

serialize

./utils/serialize

Serializes complex keys into stable string representations for cache keys.

subscribeCallback

./utils/subscribe-key

Utility to subscribe callbacks to cache key updates.

getTimestamp

./utils/timestamp

Returns current timestamps, used for deduplication and request timing.

useSWRConfig

./utils/use-swr-config

React hook to access the global SWR configuration context.

preset, defaultConfigOptions

./utils/web-preset

Predefined configuration presets for web environments.

withMiddleware

./utils/with-middleware

Utility to apply middleware functions to SWR hooks or handlers.

preload

./utils/preload

Function to preload data for a given key, useful for SSR or prefetching.

All exports from

./types

TypeScript types and interfaces used throughout the library.


Initialization Side Effects


Usage Examples

Importing the SWRConfig Context Provider

import { SWRConfig } from 'swr';

function App() {
  return (
    <SWRConfig value={{ refreshInterval: 3000 }}>
      <MyComponent />
    </SWRConfig>
  );
}

Using mutate to Manually Update Cache Data

import { mutate } from 'swr';

async function updateData() {
  // Update the cache for the key 'user/123' and revalidate
  await mutate('user/123', fetchUserData, { revalidate: true });
}

Accessing Revalidation Events

import { revalidateEvents } from 'swr';

console.log(revalidateEvents.FOCUS_EVENT);  // e.g. "focus"

Important Implementation Details


Interaction with Other Parts of the System


Mermaid Diagram: File Structure and Export Relationships

flowchart TD
    A[index.ts]
    subgraph Utils Modules
        B1[config-context.ts]
        B2[events.ts]
        B3[constants.ts]
        B4[cache.ts]
        B5[config.ts]
        B6[devtools.ts]
        B7[env.ts]
        B8[global-state.ts]
        B9[hash.ts]
        B10[helper.ts]
        B11[shared.ts]
        B12[merge-config.ts]
        B13[mutate.ts]
        B14[normalize-args.ts]
        B15[resolve-args.ts]
        B16[serialize.ts]
        B17[subscribe-key.ts]
        B18[timestamp.ts]
        B19[use-swr-config.ts]
        B20[web-preset.ts]
        B21[with-middleware.ts]
        B22[preload.ts]
    end
    subgraph Types
        C1[types.ts]
    end

    A -->|Imports & Re-exports| B1
    A -->|Imports & Re-exports| B2
    A -->|Imports & Re-exports| B3
    A -->|Re-exports| B4
    A -->|Re-exports| B5
    A -->|Imports & Calls setupDevTools()| B6
    A -->|Re-exports all| B7
    A -->|Re-exports| B8
    A -->|Re-exports| B9
    A -->|Re-exports all| B10
    A -->|Re-exports all| B11
    A -->|Re-exports| B12
    A -->|Re-exports| B13
    A -->|Re-exports| B14
    A -->|Re-exports| B15
    A -->|Re-exports| B16
    A -->|Re-exports| B17
    A -->|Re-exports| B18
    A -->|Re-exports| B19
    A -->|Re-exports| B20
    A -->|Re-exports| B21
    A -->|Re-exports| B22
    A -->|Re-exports all| C1

Summary

The index.ts file is a pivotal module that aggregates and exposes all the key building blocks of the SWR data fetching library. By re-exporting configuration providers, cache utilities, mutation helpers, event constants, serialization functions, and types, it provides a clean and convenient interface for consumers. The file also initiates developer tools integration, enhancing the developer experience throughout the application lifecycle.

This modular and declarative design supports the library's goal of efficient, cache-driven, stale-while-revalidate data fetching with strong React integration and extensibility.


End of Documentation for index.ts