middleware-preset.ts


Overview

The middleware-preset.ts file serves as a centralized aggregator and exporter of built-in middleware functions used within the SWR (stale-while-revalidate) data fetching library. Its primary purpose is to bundle essential middleware layers—specifically developer tools integration and data preloading—into a single preset array that can be easily applied to SWR hooks. This preset facilitates the seamless enhancement of core SWR functionality with additional capabilities without requiring users to individually manage or configure each middleware.


Detailed Explanation

Imports

import { use as devtoolsUse } from './devtools'
import { middleware as preload } from './preload'

Export

export const BUILT_IN_MIDDLEWARE = devtoolsUse.concat(preload)

Usage Example

To apply the built-in middleware preset in an SWR hook, you could do the following:

import useSWR from 'swr'
import { BUILT_IN_MIDDLEWARE } from './middleware-preset'

const useSWRWithPreset = withMiddleware(useSWR, ...BUILT_IN_MIDDLEWARE)

// Usage in a React component
function Profile() {
  const { data, error } = useSWRWithPreset('/api/user', fetcher)

  if (error) return <div>Error loading</div>
  if (!data) return <div>Loading...</div>
  return <div>Hello {data.name}</div>
}

Here, the BUILT_IN_MIDDLEWARE array is spread and applied to the base useSWR hook via a hypothetical withMiddleware function, which wraps the hook with the middleware chain.


Implementation Details


Interaction with the System


Mermaid Diagram: Middleware Preset Structure

flowchart LR
    subgraph middleware-preset.ts
        DT[Devtools Middleware (devtoolsUse)]
        PL[Preload Middleware (preload)]
        BI[BUILT_IN_MIDDLEWARE Array]
    end

    DT --> BI
    PL --> BI

Description: This flowchart illustrates how the BUILT_IN_MIDDLEWARE array is composed by concatenating the developer tools middleware array (devtoolsUse) with the preload middleware function (preload). The resulting BUILT_IN_MIDDLEWARE is a consolidated array of middleware functions exported for use in SWR hooks.


Summary

This simple yet critical file underpins the modular middleware system by packaging commonly used middleware together, simplifying middleware management and adoption across the SWR ecosystem.