index.js
Overview
This file implements a React component that demonstrates real-time data subscription using the useSWRSubscription hook from the SWR library. It simulates an external event-driven data source via Node.js's EventEmitter that emits data and error events asynchronously over time. The component subscribes to this event source, receiving updates every second and handling errors emitted when the data count is a multiple of three.
The primary purpose of this file is to showcase how to integrate an event-based data stream into SWR's reactive data fetching model, enabling live UI updates and error handling within a React application.
Detailed Explanation
Modules and Imports
React: Core library for building the UI component.
useSWRSubscription: SWR hook specialized for managing event-driven data subscriptions.
EventEmitter: Node.js utility used to simulate an external event source emitting asynchronous events.
Global Variables
event— an instance ofEventEmitterthat acts as the data source emittingdataanderrorevents.stopped— a boolean flag controlling the lifecycle of the event emitter loop, enabling cleanup.
Functions
async function start()
Purpose:
Simulates an external data stream that emits events every second. It emits a "data" event with a string state message every iteration, except when the iteration count is divisible by 3 (and not zero), in which case it emits an "error" event.
Parameters:
None
Returns:
Promise
Behavior:
Loops 100 times with a 1-second delay between iterations.
If
stoppedis true at any point, the function exits early to cease event emission.Emits:
"data"event with "state: " + i every second, unlessiis a multiple of 3 (excluding zero)."error"event with anErrorobject wheni % 3 === 0andi !== 0.
Usage Example:
// Starts emitting events asynchronously
start();
React Component
export default function page()
Purpose:
React functional component that subscribes to the event emitter using useSWRSubscription and displays the latest data or error.
Usage:
This component can be rendered in a React tree to observe real-time updates and error messages emitted by the simulated event source.
Key Implementation Details:
Calls
useSWRSubscriptionwith:A unique subscription key
'my-sub'.A subscription function that:
Registers listeners on the global
eventemitter for"data"and"error"events.Invokes the
nextcallback with either new data or errors to update SWR's internal state.Starts the event stream by calling
start().Returns a cleanup function setting
stoppedtotrueto halt event emission when the component unmounts, preventing memory leaks.
Returned Values from Hook:
data: The most recent data string emitted.error: An error object if an error event was emitted, otherwiseundefined.
Render Output:
Displays a heading "SWR Subscription".
Shows a descriptive subheading.
Renders the current
data.Displays the error message if an error exists.
Example Usage in JSX:
import Page from './index';
function App() {
return <Page />;
}
Important Implementation Details and Algorithms
Event-Driven Subscription Pattern:
The component leverages an event emitter to push data asynchronously to the React component via SWR's subscription hook. This pattern is more efficient and reactive than polling.Lifecycle Management:
The subscription function returns a cleanup callback to stop the event emission (stopped = true), ensuring no side effects or memory leaks when the component unmounts.Error Injection Logic:
Every third emitted value simulates an error to demonstrate error handling within the SWR subscription lifecycle.Async Delay Loop:
Thestartfunction uses a loop withawait new Promiseto create a 1-second interval between emissions, simulating real-time data arrival.
Interaction With Other System Components
SWR Library:
The file usesuseSWRSubscriptionfrom SWR, integrating the subscription model into SWR's caching and state management system.React Application:
This component can be used within any React app to demonstrate or implement real-time data streaming UI with error handling.EventEmitter as External Data Source:
Illustrates how an external event-based source can be wrapped into React state using SWR subscriptions.Examples and E2E Tests Module:
This file serves as a practical example within the broader SWR examples suite, showcasing subscription usage alongside other patterns like infinite scroll.
Visual Diagram: Flowchart of Subscription Workflow
flowchart TD
A[Component Mounts and Calls useSWRSubscription] --> B[Register 'data' and 'error' Event Listeners]
B --> C[Start EventEmitter emitting events every second]
C -->|Emit 'data' event| D[Call next(undefined, data) to update SWR state]
C -->|Emit 'error' event| E[Call next(error) to update SWR error state]
D --> F[Component re-renders displaying new data]
E --> F[Component re-renders displaying error message]
F --> G[Component Unmounts]
G --> H[Cleanup: Stop EventEmitter and Remove Listeners]
Summary
This file demonstrates an effective pattern for integrating event-based real-time data sources into React applications using SWR's subscription hook. It uses an EventEmitter to simulate asynchronous data and error events, feeding these into React state reactively. The component cleanly manages subscription lifecycle and error handling, making it a valuable reference for implementing live data streaming UIs with SWR.