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:

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:

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:

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.