manual-retry-mutate.tsx


Overview

The manual-retry-mutate.tsx file implements a React component that demonstrates a robust pattern for data fetching with error handling and manual retry capabilities using SWR (stale-while-revalidate). It combines React Suspense for asynchronous data loading, react-error-boundary for error capturing and fallback UI presentation, and SWR’s mutate function to manually trigger data refetching.

This component fetches data from a remote API endpoint (/api/retry), intentionally fails on the first attempt to simulate errors, and allows users to retry fetching manually through a UI button. The integration of Suspense and ErrorBoundary ensures smooth user experience by handling loading states and errors declaratively.


Detailed Explanation

Module Imports


Variables and Constants

let count = 0
const key = 'manual-retry-mutate'

Function: fetcher

export const fetcher = () => {
  count++
  if (count === 1) return Promise.reject('wrong')
  return fetch('/api/retry')
    .then(r => r.json())
    .then(r => r.name)
}

Usage Example:

fetcher()
  .then(data => console.log(data))
  .catch(error => console.error(error))

Hook: useRemoteData

export const useRemoteData = () =>
  useSWR(key, fetcher, {
    suspense: true
  })
const { data } = useRemoteData()
// use `data` safely; component suspends if data not ready

Component: Demo

const Demo = () => {
  const { data } = useRemoteData()
  return <div>data: {data}</div>
}

Component: Fallback

function Fallback({ resetErrorBoundary }: any) {
  return (
    <div role="alert">
      <p>Something went wrong</p>
      <button
        onClick={async () => {
          await mutate(key, fetcher)
          resetErrorBoundary()
        }}
      >
        retry
      </button>
    </div>
  )
}

Component: RemoteData (Default Export)

function RemoteData() {
  return (
    <div className="App">
      <ErrorBoundary FallbackComponent={Fallback}>
        <Suspense fallback={<div>loading</div>}>
          <Demo />
        </Suspense>
      </ErrorBoundary>
    </div>
  )
}

Important Implementation Details and Algorithms


Interaction with Other Parts of the System


Usage Example

import RemoteData from './manual-retry-mutate'

// In your app render tree
function App() {
  return <RemoteData />
}

The user will see:


Visual Diagram - Component Interaction

componentDiagram
    component RemoteData {
        +render()
    }
    component ErrorBoundary {
        +FallbackComponent
    }
    component Suspense {
        +fallback
    }
    component Demo {
        +render()
    }
    component useRemoteData {
        +fetch data (suspense enabled)
    }
    component fetcher {
        +fetch('/api/retry')
        +simulate failure first call
    }
    component mutate {
        +manual revalidation
    }

    RemoteData --> ErrorBoundary : wraps
    ErrorBoundary --> Fallback : onError
    RemoteData --> Suspense : wraps
    Suspense --> Demo : wraps
    Demo --> useRemoteData : calls
    useRemoteData --> fetcher : fetches
    Fallback --> mutate : on retry button click
    mutate --> fetcher : calls

Summary

The manual-retry-mutate.tsx file demonstrates a best-practice React pattern for data fetching with Suspense, error boundaries, and manual retry using SWR:

This pattern is valuable in scalable React applications requiring robust data fetching and error recovery mechanisms.