Providing complete React Suspense example with ErrorBoundary and retry
The user is presented with a React 18 example demonstrating the render-as-you-fetch pattern by starting data fetching via a resource outside the component, using Suspense to suspend rendering until data arrives, and an ErrorBoundary to catch fetch errors and offer a retry button that resets state and refetches. The code is a minimal single-file example showing a simulated fetch with 50% failure chance for demonstration.
Below is a minimal example of a React 18 app using Suspense with the render-as-you-fetch pattern. The data is fetched before rendering the component, and errors are handled by an ErrorBoundary that shows a retry button.
Key points:
createResource wraps a Promise so calling .read() will either return the data, throw a pending Promise (for Suspense), or throw an error.
- The fetch is started as soon as the resource is created (render-as-you-fetch).
ErrorBoundary catches errors thrown by Suspense boundaries and shows a retry button to trigger a new fetch.
You can place this code in src/index.js of a React project (e.g., created with create-react-app), then run npm start or yarn start.
import React, { Suspense, useState } from "react";
import { createRoot } from "react-dom/client";
// A small utility that creates a resource object compatible with Suspense
function createResource(fetchFn) {
let status = "pending";
let result;
const suspender = fetchFn().then(
(data) => {
status = "success";
result = data;
},
(error) => {
status = "error";
result = error;
}
);
return {
read() {
if (status === "pending") {
// Throw the promise so that <Suspense> can catch it
throw suspender;
} else if (status === "error") {
throw result;
} else if (status === "success") {
return result;
}
},
};
}
// Simulate a fetch that might fail randomly
function fetchUserSimulate() {
return new Promise((resolve, reject) => {
setTimeout(() => {
// 50% chance of failing for demonstration
if (Math.random() < 0.5) {
reject(new Error("Network error: failed to fetch user!"));
} else {
resolve({
id: 1,
name: "Ada Lovelace",
email: "ada@example.com",
});
}
}, 1200);
});
}
// A simple ErrorBoundary that shows a fallback and a retry button
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, info) {
// You could log this to a monitoring service
console.error("ErrorBoundary caught an error:", error, info);
}
resetError = () => {
this.setState({ hasError: false, error: null });
// Calls the retry function passed via props
this.props.onRetry();
};
render() {
if (this.state.hasError) {
return (
<div style={{ padding: 16, background: "#fee", color: "#900" }}>
<p>Oops! Something went wrong.</p>
<p style={{ fontSize: "0.9em" }}>{String(this.state.error)}</p>
<button onClick={this.resetError}>Retry</button>
</div>
);
}
return this.props.children;
}
}
// Component that reads data from the resource.
// It will suspend while "resource.read()" is pending, or throw an error if rejected.
function UserData({ resource }) {
const user = resource.read(); // Suspends if pending, throws error if failed
return (
<div style={{ padding: 16 }}>
<h2>User Info</h2>
<ul>
<li>ID: {user.id}</li>
<li>Name: {user.name}</li>
<li>Email: {user.email}</li>
</ul>
<p style={{ color: "#666" }}>Fetched at: {new Date().toLocaleTimeString()}</p>
</div>
);
}
function App() {
// We keep a "resource" in state so we can recreate it on retries.
const [resource, setResource] = useState(() => createResource(fetchUserSimulate));
const handleRetry = () => {
// Create a brand-new resource to trigger a new fetch
setResource(createResource(fetchUserSimulate));
};
return (
<div style={{ fontFamily: "sans-serif", padding: "20px" }}>
<h1>Render-as-You-Fetch with Suspense</h1>
<p>
This demo starts fetching as soon as the resource is created. If the fetch fails,
an error boundary displays a retry button.
</p>
<ErrorBoundary onRetry={handleRetry}>
<Suspense fallback={<div>Loading user data...</div>}>
<UserData resource={resource} />
</Suspense>
</ErrorBoundary>
</div>
);
}
const container = document.getElementById("root");
createRoot(container).render(<App />);
How it works:
createResource(fetchUserSimulate) starts fetching immediately (render-as-you-fetch).
UserData calls resource.read(). If the data isn’t ready yet, it throws the pending Promise, which Suspense uses to display the loading fallback.
- If the fetch fails,
resource.read() throws an error. ErrorBoundary catches it and renders the fallback UI with a “Retry” button.
- Clicking “Retry” creates a new resource, triggering a fresh fetch.