index.ts


Overview

This file implements the core of remote data mutation functionality within the SWR ecosystem. It defines a React hook useSWRMutation that allows components to perform manual, controlled remote mutations such as POST, PUT, DELETE, and PATCH requests. The hook handles mutation state tracking (data, error, isMutating), concurrency control to avoid race conditions, cache synchronization with SWR’s global cache, and configurable mutation behavior including optimistic updates and error handling.

The mutation logic is encapsulated as a middleware that wraps the core useSWR hook, maintaining consistency with SWR’s architecture and enabling extensibility. This file exports the hook as the default export along with relevant mutation-related types.


Detailed Explanation

Mutation Middleware Function: mutation

This is the core middleware function that adds mutation capabilities on top of the useSWR hook.

const mutation = (<Data, Error>() =>
  (
    key: Key,
    fetcher: MutationFetcher<Data>,
    config: SWRMutationConfiguration<Data, Error> = {}
  ) => { ... }
) as unknown as Middleware

Parameters

Internal State and Refs

trigger Function

const trigger = useCallback(
  async (arg: any, opts?: SWRMutationConfiguration<Data, Error>) => { ... },
  []
)
const { data, error, isMutating, trigger, reset } = useSWRMutation(
  '/api/user',
  async (url, { arg }) => {
    const response = await fetch(url, {
      method: 'POST',
      body: JSON.stringify(arg)
    })
    if (!response.ok) throw new Error('Failed to mutate')
    return await response.json()
  }
)

const onSubmit = async (formData) => {
  try {
    const result = await trigger(formData)
    console.log('Mutation result:', result)
  } catch (e) {
    console.error('Mutation error:', e)
  }
}

reset Function

const reset = useCallback(() => {
  ditchMutationsUntilRef.current = getTimestamp()
  setState({ data: UNDEFINED, error: UNDEFINED, isMutating: false })
}, [])

State Accessors

The returned object provides getters for data, error, and isMutating properties that also track which part of state is consumed to optimize component re-renders.


useSWRMutation Hook

const useSWRMutation = withMiddleware(
  useSWR,
  mutation
) as unknown as SWRMutationHook

Exported Types

The file exports mutation-related types to assist developers in typing mutation fetchers, configuration, and response objects:

These types define the contract for mutation usage, enabling strong typing and better DX.


Important Implementation Details


Interaction with Other System Parts


Visual Diagram

classDiagram
    class MutationMiddleware {
        +trigger(arg: any, opts?: SWRMutationConfiguration): Promise<Data | undefined>
        +reset(): void
        +data: Data | undefined
        +error: Error | undefined
        +isMutating: boolean
    }

    class useSWRMutation {
        +trigger(arg: any, opts?: SWRMutationConfiguration): Promise<Data | undefined>
        +reset(): void
        +data: Data | undefined
        +error: Error | undefined
        +isMutating: boolean
    }

    useSWRMutation --|> MutationMiddleware

Summary

The index.ts file implements the useSWRMutation hook, a powerful and flexible React hook to perform remote mutations integrated with SWR's caching and revalidation system. It provides:

This hook enables developers to easily perform remote mutations in React applications while maintaining UI consistency and responsiveness, fitting cleanly into the SWR ecosystem’s modular middleware architecture.