Subscription Example
Purpose
This example addresses the need for real-time data updates within React applications using the SWR library. Specifically, it demonstrates how to subscribe to an external event source (an EventEmitter) that emits data and error events asynchronously over time. Unlike traditional data fetching that polls or fetches on demand, this subscription model enables components to react instantly to streamed data changes, supporting live updates and error handling within the SWR ecosystem.
Functionality
The subscription example uses the useSWRSubscription hook to manage a continuous stream of events:
Event Source Setup: An
EventEmittersimulates an external data source, emitting a "data" event every second with incremental state and occasionally emitting "error" events when the count is divisible by 3.Subscription Logic:
The hook takes a unique key ('my-sub') and a subscription function that:Attaches listeners to the
dataanderrorevents.Calls the
nextcallback provided by the hook to propagate new data or errors to the SWR state.Starts the event emission asynchronously.
Returns a cleanup function to stop the event emission when the component unmounts.
State Updates and Error Handling:
The hook internally manages the subscription lifecycle, updating thedataanderrorvalues returned to the component whenever new events occur.Rendering:
The React component displays the latest received data and any error messages, demonstrating real-time UI updates driven by the subscription.
Key Code Interaction Snippet
const { data, error } = useSWRSubscription('my-sub', (key, { next }) => {
event.on("data", (value) => next(undefined, value))
event.on("error", (err) => next(err))
start()
return () => {
stopped = true
}
})
Here, the subscription callback:
Registers event listeners that push updates via
next.Initiates the event stream with
start().Provides a cleanup callback to stop the emitter.
Integration
This subscription example complements the main SWR functionality by extending the core data fetching paradigm to support real-time event-driven scenarios. While the core useSWR hook handles request-response asynchronous fetching with caching and revalidation, useSWRSubscription enables continuous, push-based data streams.
It integrates smoothly with other SWR subtopics:
Middleware Architecture: The subscription hook can be composed with middleware layers to add features like caching, error retry, or devtools.
Error Handling and Retry Logic: Errors emitted by the event source are surfaced through the hook, allowing React components to handle them cleanly.
Developer Tooling and Debugging: Subscription updates can be traced in devtools integrated with SWR to monitor real-time data flows.
Examples and E2E Tests: This example illustrates a practical use case for subscriptions, complementing other example scenarios such as infinite loading or mutations.
By bridging event-driven data sources with SWR's declarative React hooks, the subscription example highlights how live data can be seamlessly integrated into SWR-powered applications.
Diagram
Below is a flowchart illustrating the core 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]
This diagram captures the continuous cycle of event subscription, data/error propagation, UI update, and resource cleanup.
This subscription example showcases how to harness event emitters within the SWR ecosystem, enabling efficient and reactive real-time data handling in React applications.