manual-retry.tsx
Overview
manual-retry.tsx is a React component module designed to fetch and display remote data with built-in support for error handling and manual retrying. It leverages React Suspense and error boundaries to manage asynchronous data loading and recovery from errors gracefully. The file includes a demo component that displays fetched data and provides a user interface to retry the fetch operation if it fails.
Key features:
Uses a custom hook
useRemoteDatato fetch remote data.Implements
Suspenseto show a loading state while data is being fetched.Wraps the data-fetching component in an
ErrorBoundaryto catch runtime errors.Provides a fallback UI with a "retry" button that resets the error boundary and triggers a fresh fetch.
Preloads remote data to optimize initial rendering.
This file serves as a reusable and robust example of how to combine React Suspense and error boundaries for reliable data fetching with manual retry capabilities.
Detailed Explanation
Imports
Suspensefrom React: For showing fallback content while waiting for asynchronous data.ErrorBoundaryfromreact-error-boundary: To catch errors in rendering or lifecycle methods and show fallback UI.useRemoteDataandpreloadRemote: Custom hooks/utilities for fetching and preloading remote data.
Functions and Components
Demo
const Demo = () => {
const { data } = useRemoteData()
return <div>{data}</div>
}
Purpose: This functional component uses the
useRemoteDatahook to retrieve remote data and renders it inside a<div>.Parameters: None.
Returns: JSX element displaying the fetched data.
Usage: Used inside the Suspense boundary to display data once loaded.
Fallback
function Fallback({ resetErrorBoundary }: any) {
return (
<div role="alert">
<p>Something went wrong:</p>
<button
onClick={() => {
resetErrorBoundary()
}}
>
retry
</button>
</div>
)
}
Purpose: Provides a fallback UI when an error occurs inside the
ErrorBoundary.Parameters:
resetErrorBoundary(function): Provided byreact-error-boundary, this function resets the error state.
Returns: JSX element showing an error message and a retry button.
Usage: Passed as the
FallbackComponentto theErrorBoundary.Behavior: Clicking the "retry" button calls
resetErrorBoundary, which triggers the boundary to reset and attempt rendering again.
RemoteData
function RemoteData() {
return (
<div className="App">
<ErrorBoundary
FallbackComponent={Fallback}
onReset={() => {
preloadRemote()
}}
>
<Suspense fallback={<div>loading</div>}>
<Demo />
</Suspense>
</ErrorBoundary>
</div>
)
}
Purpose: Main exported component which orchestrates data fetching, error handling, and suspense fallback.
Parameters: None.
Returns: JSX element that wraps the
Democomponent with error and loading handling.Usage: Imported and rendered in application UI where remote data is needed.
Detailed behavior:
Wraps
DemowithSuspense, showing a simple "loading" message while data loads.Wraps
Suspensewith anErrorBoundary, displaying theFallbackUI if an error occurs.The
onResetcallback ofErrorBoundarytriggerspreloadRemote(), which reloads the remote data before retrying.
Integration:
Uses
preloadRemoteto preload the remote data on reset to improve user experience.Relies on
useRemoteDatafor the actual data fetching.
Utility Function Calls
preloadRemote()
Called once at the top-level to initiate preloading of remote data before the component mounts.
Called again in the
onResethandler ofErrorBoundaryto refresh the data after a retry.
Implementation Details and Algorithms
Data Fetching with Suspense: The
useRemoteDatahook likely uses React Suspense-compatible data fetching which suspends rendering until data is ready. This pattern enhances user experience by allowing declarative loading states.Error Handling with Error Boundary: The
ErrorBoundarycomponent catches errors in child components, preventing the entire app from crashing and providing fallback UI with retry capability.Manual Retry: The
Fallbackcomponent exposes a "retry" button which resets the error boundary state (usingresetErrorBoundary), triggering theonResethandler that preloads the data again. This manual retry approach allows users to explicitly recover from transient errors.Preloading Strategy: Calling
preloadRemote()before initial render and on reset primes the data cache or triggers fetch requests ahead of rendering, reducing wait times.
Interaction with Other Parts of the System
use-remote-data.ts: The file depends on
useRemoteDataandpreloadRemotefrom./use-remote-data. This dependency encapsulates the remote data fetching logic and caching/preloading mechanisms.React and React-error-boundary: Leverages React's Suspense API and the
react-error-boundarylibrary for error handling.Parent Application: The exported
RemoteDatacomponent can be integrated into the UI wherever remote data with retry logic is needed.
Usage Example
import RemoteData from './manual-retry'
function App() {
return (
<div>
<h1>My Remote Data Display</h1>
<RemoteData />
</div>
)
}
In this example, RemoteData will fetch data asynchronously, show a loading message while fetching, display data once loaded, and provide a manual retry button if the fetch fails.
Visual Diagram
componentDiagram
component RemoteData {
+render()
}
component ErrorBoundary {
+FallbackComponent
+onReset()
}
component Suspense {
+fallback
}
component Demo {
+render()
+useRemoteData()
}
component Fallback {
+render()
+retryButton(onClick: resetErrorBoundary)
}
RemoteData --> ErrorBoundary : wraps
ErrorBoundary --> Fallback : fallback UI
ErrorBoundary --> Suspense : wraps
Suspense --> Demo : renders
Demo --> useRemoteData : calls hook
Fallback --> ErrorBoundary : resetErrorBoundary called triggers onReset
onReset --> preloadRemote : called on reset
Summary
The manual-retry.tsx file defines a React component (RemoteData) that fetches remote data with automatic loading indicators and robust error handling via an error boundary with manual retry support. It uses Suspense for asynchronous rendering and reuses preloadRemote to optimize data fetching on initial load and retries.
This setup provides an elegant pattern for handling unreliable network requests or flaky data sources, improving user experience by allowing manual recovery from errors without needing a full page reload.